java 将5mb以内图片压缩至200kb以下

您所在的位置:网站首页 jpg图片转为小于300k java 将5mb以内图片压缩至200kb以下

java 将5mb以内图片压缩至200kb以下

2024-07-01 10:57| 来源: 网络整理| 查看: 265

package com.qizhi.itfin.controller.mmb;

import java.io.File; import java.io.IOException;

import com.qizhi.itfin.common.util.ThumbnailUtils;

public class test {

    public static void main(String[] args) {

        //网络路径地址         String url = "http://192.168.18。。。:81/upload/img//18/3/b4/ba/e9/37/c7/f7/b4bae937c7f7edf048af44e619d18ef4.jpg";

        url = pictureCompression(url);         System.err.println(url);     }

    private static String pictureCompression(String photoUrl) {         String urls = "http://192.168.18.。。。:81/upload/img/";

       //物理路径         String path = "X:/img/";

        // 替换后的图片url         photoUrl = photoUrl.replace(urls, path);         // 图片小数点之前的数据         String intNumber = photoUrl.substring(0, photoUrl.indexOf("."));         // 图片小数点之后的数据         String lastFileName = photoUrl.substring(photoUrl.lastIndexOf("."));         // 压缩图片新的路径         String existPhoto = intNumber + "-thumbnail" + lastFileName;         // 判断之前是否有生成的压缩图片         File existPhotoFile = new File(existPhoto);         String pcZipUrls = null;         String slash = "\\";         String leftSlash = "/";         String canonicalPath = null;         System.out.println("【压缩图片】物理地址头部信息  " + path);         System.out.println("【压缩图片】网络地址头部信息  " + urls);         System.out.println("【压缩图片】转化前的图片路径  " + photoUrl);         if (existPhotoFile.exists()) {             try {                 canonicalPath = existPhotoFile.getCanonicalPath();             } catch (IOException e) {                 e.printStackTrace();                 System.out.println("【压缩图片】图片服务器中已经存在exception  " + e);             }             pcZipUrls = canonicalPath.replace(slash, leftSlash);             photoUrl = pcZipUrls.replace(path, urls);             System.out.println("【压缩图片】图片服务器中已经存在  " + photoUrl);         } else {             File file = new File(photoUrl);             try {                 File makeThumbnail = ThumbnailUtils.makeThumbnail(file, existPhotoFile);                 // 转化成String类型的url                 canonicalPath = makeThumbnail.getCanonicalPath();                 pcZipUrls = canonicalPath.replace(slash, leftSlash);                 photoUrl = pcZipUrls.replace(path, urls);                 System.out.println("【压缩图片】转化后的图片路径  " + photoUrl);             } catch (IOException e) {                 e.printStackTrace();                 System.out.println("【压缩图片】转化后的图片路径exception  " + e);             }         }         return photoUrl;     }

}  

图片压缩Utils类

   /**      * 图片压缩缩略图      *       * @param oldFile      * @param newFile      * @return      * @throws IOException      */     public static File makeThumbnail(File oldFile, String uri) throws IOException {         long fileSize = oldFile.length();         File resultFile = oldFile;         String fileUri = uri.substring(0, uri.lastIndexOf("."));         File newFile = new File(fileUri);         File newExistFile = new File(uri);         // 格式转换成jpg         String lastFileName = oldFile.getName().substring(oldFile.getName().lastIndexOf(".")).toLowerCase();         if (!StringUtils.equals(lastFileName, ".jpg")) {             Thumbnails.of(oldFile).scale(1f).outputFormat("jpg").outputQuality(0.8f).toFile(newFile);             fileSize = newExistFile.length();             resultFile = newExistFile;         }         // 处理文件大小到200K以下         if (fileSize >= MAX_SIZE) {             // 第一次将图片尺寸变小,高度固定480             Thumbnails.of(oldFile).height(480).outputFormat("jpg").outputQuality(0.8f).toFile(newFile);             fileSize = newExistFile.length();             // 一般这时图片就在200K以下了,以防万一,循环压缩质量,直到200KB以下             while (fileSize > MAX_SIZE) {                 Thumbnails.of(newExistFile).scale(1D).outputFormat("jpg").outputQuality(0.8f).toFile(newFile);                 fileSize = newExistFile.length();             }             resultFile = newExistFile;         }         return resultFile;     }

 

另外一种图片压缩方式(内存流) 并 转成base64

package com.qizhi.itfin.controller.gps;

import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.tomcat.util.codec.binary.Base64;

public class test {

    public static void main(String[] args) {         try {             String convertImageToBase64 = convertImageToBase64(                 "http://*********/upload/img//18/3/f4/74/90/ff/af/6f/f47490ffaf6f89d027dfe59cfa9e9fda.jpg",                 200);             System.err.println(convertImageToBase64);         } catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }     }

    /**      * 将图片转换为base64格式      *      * @param imageUrl:图片路径      * @param sizeLimit:原图大小上限,当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb      * @return      */     public static String convertImageToBase64(String imageUrl, Integer sizeLimit) throws IOException {         // 默认上限为500k         if (sizeLimit == null) {             sizeLimit = 500;         }         sizeLimit = sizeLimit * 1024;         String base64Image;         DataInputStream dataInputStream = null;         ByteArrayOutputStream outputStream = null;         ByteArrayInputStream inputStream = null;         try {             // 从远程读取图片             URL url = new URL(imageUrl);             dataInputStream = new DataInputStream(url.openStream());             outputStream = new ByteArrayOutputStream();             byte[] buffer = new byte[2048];             int length;             while ((length = dataInputStream.read(buffer)) > 0) {                 outputStream.write(buffer, 0, length);             }             byte[] context = outputStream.toByteArray();

            // 将图片数据还原为图片             inputStream = new ByteArrayInputStream(context);             BufferedImage image = ImageIO.read(inputStream);             int imageSize = context.length;             int type = image.getType();             int height = image.getHeight();             int width = image.getWidth();

            BufferedImage tempImage;             // 判断文件大小是否大于size,循环压缩,直到大小小于给定的值

            System.out.println(sizeLimit);             while (imageSize > sizeLimit) {                 System.err.println(imageSize);                 // 将图片长宽压缩到原来的90%                 height = new Double(height * 0.9).intValue();                 width = new Double(width * 0.9).intValue();                 tempImage = new BufferedImage(width, height, type);                 // 绘制缩小后的图                 tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);                 // 重新计算图片大小                 outputStream.reset();                 ImageIO.write(tempImage, "jpg", outputStream);                 imageSize = outputStream.toByteArray().length;

            }

            // 将图片转化为base64并返回             byte[] data = outputStream.toByteArray();             File destFile = new File("X:\\vedio\\456.jpg");             FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流             out.write(data);             out.close();             // 此处一定要使用org.apache.tomcat.util.codec.binary.Base64,防止再linux上出现换行等特殊符号             base64Image = Base64.encodeBase64String(data);         } catch (Exception e) {             // 抛出异常             throw e;         } finally {             if (dataInputStream != null) {                 try {                     dataInputStream.close();                 } catch (IOException e) {                     e.printStackTrace();                 }             }             if (outputStream != null) {                 try {                     outputStream.close();                 } catch (IOException e) {                     e.printStackTrace();                 }             }             if (inputStream != null) {                 try {                     inputStream.close();                 } catch (IOException e) {                     e.printStackTrace();                 }             }         }         return base64Image;     }

}

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3