照片压缩工具类

 <!--照片压缩-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.13</version>
        </dependency>
package org.dlax.utils;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author l
 * @version 1.0
 * @PACKAGE_NAME: org.dlax.utils
 * @date 2022/3/24 09:46 周四
 * 照片处理工具
 */
@Slf4j
public class ThumbnailatorUtils {

    /**
     * 修改像素,这里改为100px*100px
     * @param path    //现在路径
     * @param newPath  //处理过后的路径
     * @return
     */
    public static boolean modifyPixel(String path,String  newPath)  {
        try {
            File fromFile = new File(path);
            if(!fromFile.exists()){
                Thumbnails.of(fromFile).size(100,100)
                        .toFile(newPath);
            }
            return  true;
        }catch (Exception ex){
            log.error("修改像素失败:" + ex.getMessage());
        }
        return  false;
    }

    public static void main(String[] args) {
        String urlpath ="http://ip/dn/photo/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220324141303.jpg";
        Map<String, String> map = base64File(urlpath);
    }


    /**
     *url请求地址转压缩完后,转成base64
     * @param urlpath
     * @return
     */
    public static Map<String, String>  base64File(String urlpath)  {
        Map<String, String> stringMap = new HashMap<>();
        //对本地文件命名
        String fileName = urlpath.substring(urlpath.lastIndexOf("."), urlpath.length());
        String strNetImageToBase64 =null;
        try {
            //将url转成file文件
            File file = getFile(urlpath);
            byte [] buf = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            //进行压缩处理
            Thumbnails.of(file.getAbsoluteFile()).scale(0.5f).toOutputStream(outputStream);
            buf = outputStream.toByteArray();
            strNetImageToBase64 = new BASE64Encoder().encode(buf);
            byteArrayToFile(buf,"C:\\images\\yansu.jpg");
            //计算大小
            double vbase64 = base64FileSize(strNetImageToBase64);
            log.info("图片大小:"+vbase64);
        }catch (Exception ex){
            log.error("转成base64失败:" + ex.getMessage());
        }
        stringMap.put("fileName", fileName);
        stringMap.put("strNetImageToBase64", strNetImageToBase64);
        return  stringMap;
    }

    /**
     * 字节数组写出到图片
     * @param src
     * @param filePath
     */
    public static void byteArrayToFile(byte[] src,String filePath) {
        File dest = new File(filePath);
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new ByteArrayInputStream(src);
            os = new FileOutputStream(dest);
            //缓冲容器
            byte[] flush = new byte[5];
            int len;
            while((len=is.read(flush))!=-1) {
                os.write(flush,0,len);
            }
            os.flush();
        } catch (IOException e) {
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e2) {
            }
        }
    }

   /**
     * 将url转成file文件
     * @param url
     * @return
     */
    public static File getFile(String url) {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."),url.length());
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            String tempFilePath="home/tmpphoto/";
            File tempDir = new File( tempFilePath );
            //判断文件夹是否存在
            if (!tempDir.exists() && !tempDir.isDirectory()) {
                //不存在的话,创建文件夹
                tempDir.mkdirs();
            }
            file = File.createTempFile("net_url", fileName,tempDir);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            log.error("将url转成file文件失败:"+ e.getMessage());
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                log.error("关闭文件失败:"+ e.getMessage());
            }
        }
        return file;
    }
    /**
     * 精确计算base64字符串文件大小(单位:B)
     * @param base64String
     * @return
     */
    public static double base64FileSize(String base64String) {
        /**检测是否含有base64,文件头)*/
         base64String = base64String.substring(base64String.lastIndexOf(",")+1);
        /** 获取base64字符串长度(不含data:audio/wav;base64,文件头) */
        int size0 = base64String.length();
        /** 获取字符串的尾巴的最后10个字符,用于判断尾巴是否有等号,正常生成的base64文件'等号'不会超过4个 */
        String tail = base64String.substring(size0 - 10);
        /** 找到等号,把等号也去掉,(等号其实是空的意思,不能算在文件大小里面) */
        int equalIndex = tail.indexOf("=");
        if (equalIndex > 0) {
            size0 = size0 - (10 - equalIndex);
        }
        /** 计算后得到的文件流大小,单位为字节 */
        return size0 - ((double) size0 / 8) * 2;
    }

    /**
     * 按比例缩小
     * @param path    //现在路径
     * @param newPath  //处理过后的路径
     * @return
     */
    public static boolean scaleDown(String path,String  newPath)  {
        try {
            File fromFile = new File(path);
            if(fromFile.exists()){
                Thumbnails.of(fromFile).scale(0.5f)
                .toFile(newPath);
                return  true;
            }
        }catch (Exception ex){
            log.error("按比例缩小失败:" + ex.getMessage());
        }
        return  false;
    }

    /**
     * 尺寸不变,修改文件大小
     * @param path    //现在路径
     * @param newPath  //处理过后的路径
     * @return
     */
    public static boolean modifyFileSize(String path,String  newPath)  {
        try {
            File fromFile = new File(path);
            if(fromFile.exists()){
                Thumbnails.of(fromFile).scale(1).outputQuality(0.2f)
                        .toFile(newPath);
                return  true;
            }

        }catch (Exception ex){
            log.error("尺寸不变,修改文件大小失败:" + ex.getMessage());
        }
        return  false;
    }
    /**
     * 加水印,需指定水印图片和透明度
     * @param path    //现在路径
     * @param newPath  //处理过后的路径
     * @return
     */
    public static boolean specifyWatermarkPicture(String path,String  newPath)  {
        try {
            File fromFile = new File(path);
            if(fromFile.exists()){
                Thumbnails.of(fromFile).scale(1).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(fromFile),0.5f)
              .toFile(newPath);
                return  true;
            }

        }catch (Exception ex){
            log.error("加水印,需指定水印图片和透明度失败:" + ex.getMessage());
        }
        return  false;
    }
    /**
     * 加水印,水印为自定义文字
     * @param path    //现在路径
     * @param text    //自定义文字
     * @param newPath  //处理过后的路径
     * @return
     */
    public static boolean customtext(String text,String path,String  newPath)  {
        try {
            File fromFile = new File(path);
            if(fromFile.exists()){
                BufferedImage bi = new BufferedImage(80,30,BufferedImage.TYPE_INT_BGR);
        Graphics2D g = bi.createGraphics();
        g.setColor(Color.lightGray);
        g.drawRect(0,0,80,30);
        g.drawString(text, 15,15);
        Thumbnails.of(fromFile).scale(1).watermark(Positions.BOTTOM_RIGHT, bi,0.3f)
                .toFile(newPath);
                return  true;
            }

        }catch (Exception ex){
            log.error("加水印,水印为自定义文字失败:" + ex.getMessage());
        }
        return  false;
    }

    /**
     * 转换图片格式
     * @param path    //现在路径
     * @param newPath  //处理过后的路径
     * @return
     */
    public static boolean convertPictureFormat(String path,String  newPath)  {
        try {
            File fromFile = new File(path);
            if(fromFile.exists()){
                Thumbnails.of(fromFile).scale(1).outputFormat("png")
                .toFile(newPath);
                return  true;
            }

        }catch (Exception ex){
            log.error("转换图片格式失败:" + ex.getMessage());
        }
        return  false;
    }
    /**
     * 图片裁减
     * @param path    //现在路径
     * @param newPath  //处理过后的路径
     * @return
     */
    public static boolean imageReduction(String path,String  newPath)  {
        try {
            File fromFile = new File(path);
            if(fromFile.exists()){
                Thumbnails.of(fromFile).sourceRegion(0, 0, 200, 200).size(200,200)
                .toFile(newPath);
                return  true;
            }

        }catch (Exception ex){
            log.error("图片裁减失败:" + ex.getMessage());
        }
        return  false;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Android图片压缩工具类是一种用于压缩Android应用中的图片文件的工具。根据引用和引用的内容,这个工具类的具体实现可能包括以下功能: - 通过将图片文件转换为字节数组,以便进行后续的压缩处理。 - 使用缓冲输出流将压缩后的图片数据写入输出流中。 - 通过设置合适的压缩参数,对图片进行压缩操作,减小文件大小但尽量保持良好的图像质量。 - 可能还包括一些其他的图像处理操作,如旋转、裁剪等。 具体的实现细节可以参考引用和引用提供的代码示例。在这些示例中,使用了ByteArrayInputStream和ByteArrayOutputStream类来处理字节数组的输入和输出。通过设置合适的压缩参数,可以实现对图片的压缩操作。此外,还可以使用BufferedOutputStream类来提高输出流的写入性能。 如果想要进一步了解关于Android图片压缩工具类的使用和实现细节,可以参考引用提供的配套资料,该资料可能提供了更详细的解释和示例代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Android开发之图片压缩工具类完整实例](https://download.csdn.net/download/weixin_38517904/14018839)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [android图片压缩工具类分享](https://download.csdn.net/download/weixin_38616330/14881444)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Spring Boot(六十四):SpringBoot集成Gzip压缩数据](https://download.csdn.net/download/u013938578/88221156)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南大白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值