io获取本地图片并进行压缩然后转换base64编码

it2026-03-15  4

io获取本地图片并进行压缩然后转换base64编码

@Test public void test5() throws Exception { String imgUrl = "http://sy1.iknowmuch.com/ishelf/imgs/upload/product/debug_esl.png"; String imgdist = "C:\\ishelf\\imgs"; String imgUrlFile = templateCenterService.imgUrlFile(imgdist, imgUrl); File distfile = new File(imgUrlFile); BufferedImage src = ImageIO.read(distfile); System.out.println("没压缩前大小:"+distfile.length()); if(distfile.length()>=3000){ int [] widthAndHeight = new int[2]; widthAndHeight[0] = (int)src.getWidth(null); widthAndHeight[1] = (int) src.getHeight(null); reduceImg(imgUrlFile,widthAndHeight,(int)src.getWidth(null),(int) src.getHeight(null),null); System.out.println(distfile.length()); } System.out.println("字节码:"+getImageBinary(imgUrlFile)); } /** * 压缩图片 * @param imgsrc * @param widthAndHeight * @param widthdist * @param heightdist * @param rate */ public static void reduceImg(String imgsrc,int []widthAndHeight, int widthdist, int heightdist, Float rate) { try { File srcfile = new File(imgsrc); // 检查图片文件是否存在 if (!srcfile.exists()) { System.out.println("文件不存在"); } // 如果比例不为空则说明是按比例压缩 if (rate != null && rate > 0) { //获得源图片的宽高存入数组中 if (widthAndHeight == null || widthAndHeight[0] == 0 || widthAndHeight[1] == 0) { return; } else { //按比例缩放或扩大图片大小,将浮点型转为整型 widthdist = (int) (widthAndHeight[0] * rate); heightdist = (int) (widthAndHeight[1] * rate); } } // 开始读取文件并进行压缩 Image src = ImageIO.read(srcfile); // 构造一个类型为预定义图像类型之一的 BufferedImage BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB); //绘制图像 getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像 //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。 tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null); //创建文件输出流 FileOutputStream out = new FileOutputStream(imgsrc); //将图片按JPEG压缩,保存到out中 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); //关闭文件输出流 out.close(); } catch (Exception ef) { ef.printStackTrace(); } } public static String getImageBinary(String imageUrl) { String data = null; try { //int HttpResult = 0; // 服务器返回的状态 File imageFile = new File(imageUrl); InputStream inStream = new FileInputStream(imageFile); byte[] btImg = readInputStream(inStream); data = Base64.encode(btImg); } catch (Exception e) { e.printStackTrace(); } return data; }
最新回复(0)