在實(shí)際開(kāi)發(fā)中,通常需要同時(shí)上傳圖片和視頻。Java提供了豐富的類庫(kù)和工具來(lái)實(shí)現(xiàn)這一目標(biāo)。
所需工具:
javax.imageio imageio-core 1.0 org.bytedeco javacv 1.5.5
上傳圖片:
//獲取文件擴(kuò)展名 String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //使用ImageIO讀取圖片 BufferedImage image = ImageIO.read(file.getInputStream()); //將BufferedImage轉(zhuǎn)換成ByteArrayOutputStream ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, ext, baos); //將ByteArrayOutputStream轉(zhuǎn)換成byte數(shù)組 byte[] bytes = baos.toByteArray(); //將byte數(shù)組上傳到服務(wù)器 fileService.upload(bytes);
上傳視頻:
//獲取文件擴(kuò)展名 String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //根據(jù)擴(kuò)展名確定視頻格式 int videoFormat; if (".mp4".equals(ext)) { videoFormat = org.bytedeco.javacpp.avutil.AV_PIX_FMT_YUV420P; } else if (".flv".equals(ext)) { videoFormat = org.bytedeco.javacpp.avutil.AV_PIX_FMT_BGR24; } else { throw new Exception("不支持的視頻格式"); } //使用JavaCV獲取視頻幀 FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(file.getInputStream()); grabber.start(); Frame frame; FrameRecorder recorder = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { //創(chuàng)建錄制器 recorder = FrameRecorder.createDefault(fileService.getFilePath(), grabber.getImageWidth(), grabber.getImageHeight()); recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); recorder.setFormat("mp4"); recorder.setFrameRate(grabber.getFrameRate()); recorder.setVideoQuality(1.0); recorder.start(); while ((frame = grabber.grabFrame()) != null) { Java2DFrameConverter converter = new Java2DFrameConverter(); BufferedImage bufferedImage = converter.getBufferedImage(frame); //將BufferedImage轉(zhuǎn)換成ByteArrayOutputStream baos.reset(); ImageIO.write(bufferedImage, "jpg", baos); //將ByteArrayOutputStream轉(zhuǎn)換成byte數(shù)組 byte[] bytes = baos.toByteArray(); //將byte數(shù)組編碼成視頻 byte[] yuvBytes = new byte[bytes.length / 3 * 2]; //使用JavaCV進(jìn)行編碼 recorder.record(converter.convert(bufferedImage), videoFormat); } } finally { if (recorder != null) { recorder.stop(); recorder.release(); } grabber.stop(); }