/** * 视频压缩 需要jave jar 包。到网上下载即可 * * @param source 需要压缩的视频 * @param targetPath 压缩的目标路径 * @return */ public static boolean compressVideo(File source, String targetPath) { System.out.println("source:" + source); System.out.println("targetPath:" + targetPath); try { // 编码器 Encoder encoder = new Encoder(); // 源视频的信息 MultimediaInfo mInfo = encoder.getInfo(source); AudioInfo audioInfo = mInfo.getAudio(); VideoInfo videoInfo = mInfo.getVideo(); // 音频参数设置(一些参数都是使用源视频) AudioAttributes audio = new AudioAttributes(); audio.setBitRate(44100); audio.setChannels(audioInfo.getChannels()); audio.setSamplingRate(audioInfo.getSamplingRate()); audio.setCodec("libmp3lame"); audio.setVolume(256);// 256表示原声,小于表示减少音量 大于表示增加音量 // 视频参数设置(一些参数都是使用源视频) VideoAttributes video = new VideoAttributes(); video.setCodec("mpeg4"); video.setBitRate(videoInfo.getBitRate()); // VideoSize size = new VideoSize(720, 960); // video.setSize(size); video.setFrameRate(30); // 视频转码编码设置 EncodingAttributes attrs = new EncodingAttributes(); attrs.setFormat("mp4"); attrs.setAudioAttributes(audio); attrs.setVideoAttributes(video); System.out.println("audioInfo:" + audioInfo); System.out.println("videoInfo:" + videoInfo); System.out.println("mInfo" + mInfo); File target = new File(targetPath); String decoderstr = videoInfo.getDecoder(); System.out.println("decoderstr:" + decoderstr); String[] decoder = encoder.getSupportedDecodingFormats(); List<String> list = new ArrayList<String>(); for (int i = 0; i < decoder.length; i++) { list.add(decoder[i]); } // 如果视频解码方式存在就编码。不然就不用 // 。。查看解码格式类型:http://www.sauronsoftware.it/projects/jave/manual.php#3.1 if (list.contains(decoderstr)) { encoder.encode(source, target, attrs); logger.info("压缩完成..."); } else { logger.info("不支持该编码的视频,编码为:{};提示:压缩失败", decoderstr); } } catch (EncoderException e) { logger.info("视频压缩出现异常"); e.printStackTrace(); } return false; } /** * 图片压缩 * * @param source * @param target */ public static void compressPicture(File source, String targetPath) { try { System.out.println("文件:" + source + "临时文件路径:" + targetPath); System.out.println("begin compress picture。。。。"); FileOutputStream fos = new FileOutputStream(targetPath); BufferedImage bi = ImageIO.read(source); int srcWidth = bi.getWidth(); int srcHeight = bi.getHeight(); Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.setColor(Color.RED); g.drawImage(image, 0, 0, null); g.dispose(); ImageIO.write(tag, "jpg", fos); System.out.println("end compress picture。。。。"); } catch (IOException e) { e.printStackTrace(); } } }