在實際開發中,通常需要同時上傳圖片和視頻。Java提供了豐富的類庫和工具來實現這一目標。
所需工具:
javax.imageio imageio-core 1.0 org.bytedeco javacv 1.5.5
上傳圖片:
//獲取文件擴展名 String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //使用ImageIO讀取圖片 BufferedImage image = ImageIO.read(file.getInputStream()); //將BufferedImage轉換成ByteArrayOutputStream ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, ext, baos); //將ByteArrayOutputStream轉換成byte數組 byte[] bytes = baos.toByteArray(); //將byte數組上傳到服務器 fileService.upload(bytes);
上傳視頻:
//獲取文件擴展名 String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //根據擴展名確定視頻格式 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 { //創建錄制器 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轉換成ByteArrayOutputStream baos.reset(); ImageIO.write(bufferedImage, "jpg", baos); //將ByteArrayOutputStream轉換成byte數組 byte[] bytes = baos.toByteArray(); //將byte數組編碼成視頻 byte[] yuvBytes = new byte[bytes.length / 3 * 2]; //使用JavaCV進行編碼 recorder.record(converter.convert(bufferedImage), videoFormat); } } finally { if (recorder != null) { recorder.stop(); recorder.release(); } grabber.stop(); }