Java——批量更改图片像素(大小)

在小程序开发中,资源加载会影响界面绘制;假如网络状态不够好,
很可能会引起初始化界面为空,直到图片加载完成才显示整个界面。

我们知道,小程序代码及资源本身的限制为2MB,缓存限制为10MB,
因此可以考虑将列表项所需的大量图片通过更改像素的方式大大减小其大小。
例如一张2MB的图片可以缩小至2KB。

那么如何批量更改大量图片的像素又不改变其比例呢?
作为一个程序员当然要用代码来实现,在此介绍一下如何通过Java更改图片像素

题外话

在Windows系统获取的文件路径由于其中的\往往不能直接在代码中使用,
因此介绍一下如何替换字符串中的\(反斜杠):
对String对象使用.replaceAll("\\\\","/")即可将所有\替换为/,进而方便文件的使用。

· 获取图片像素

import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageResizer {

    ...

    /**
     * 功能:获取图片像素
     * * @param filePath 图片路径
     */
    public static void getPixel(String filePath){
        File file = new File(filePath);
        BufferedImage bi = null;
        try {
        bi = ImageIO.read(file);
        } catch (Exception e) {
        e.printStackTrace();
        }
        int width = bi.getWidth(); // 像素
        int height = bi.getHeight(); // 像素
        System.out.println("width=" + width + ",height=" + height + ".");
    }

    ...

    public static void main(String []args){
        getPixel("G:/蝴蝶识别/压缩/首图/Acraea terpsicore0.jpg");
    }
}

结果:

width=450,height=470.

· 更改图片像素

按图片的原比例进行修改:

    /**
     * @param srcPath  源图片路径
     * @param desPath  修改大小后图片路径 
     * @param scaleSize 图片的修改比例,目标宽度
     */  
    public static void resizeImage(String srcPath, String desPath,int scaleSize) throws IOException {  

        File srcFile = new File(srcPath);  
        Image srcImg = ImageIO.read(srcFile);  
        BufferedImage bi = null;
        try {
        bi = ImageIO.read(srcFile);
        } catch (Exception e) {
        e.printStackTrace();
        }
        float width = bi.getWidth(); // 像素
        float height = bi.getHeight(); // 像素
        float scale=width/scaleSize;
        BufferedImage buffImg = null;  
        buffImg = new BufferedImage(scaleSize, (int)(height/scale), BufferedImage.TYPE_INT_RGB); 
        //使用TYPE_INT_RGB修改的图片会变色 
        buffImg.getGraphics().drawImage(  
                srcImg.getScaledInstance(scaleSize, (int)(height/scale), Image.SCALE_SMOOTH), 0,  
                0, null);  

        ImageIO.write(buffImg, "JPEG", new File(desPath));
    }  

    public static void main(String []args) throws IOException{ 
        getFiles("G:/蝴蝶识别/压缩/shoutu","modified_100",100);//将图片压缩至100宽
    }

按自定义宽高修改:

    /**
     * 
     * @param srcPath 原图片路径 
     * @param desPath  转换大小后图片路径 
     * @param width   转换后图片宽度 
     * @param height  转换后图片高度 
     */  
    public static void resizeImage(String srcPath, String desPath,  
            int width, int height) throws IOException {  

        File srcFile = new File(srcPath);  
        Image srcImg = ImageIO.read(srcFile);  
        BufferedImage buffImg = null;  
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //使用TYPE_INT_RGB修改的图片会变色 
        buffImg.getGraphics().drawImage(  
                srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,  
                0, null);  

        ImageIO.write(buffImg, "JPEG", new File(desPath));  
    }  

批量修改

    /**
     * @param srcPath  源图片文件夹路径
     * @param desPath  修改大小后图片文件夹路径 
     * @param scaleSize 图片的修改比例,目标宽度
     */
    public static void getFiles(String path,String modPath,int scaleSize) throws IOException {
        ArrayList<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        //循环读取目录下图片
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) { 
                  System.out.println("文件:" + tempList[i].getName()+"-"+tempList[i].getAbsolutePath().replaceAll("\\\\","/"));
                  String[] imagePath=tempList[i].getAbsolutePath().replaceAll("\\\\","/").split("/");
                  String imageNumber=null;        
            ImageResizer.resizeImage(tempList[i].getAbsolutePath().replaceAll("\\\\","/"),"目标文件路径",scaleSize);  
                files.add(tempList[i].toString());
            }
            if (tempList[i].isDirectory()) {
//                  System.out.println("文件夹:" + tempList[i]);
            }
        }
        System.out.println(path+"下文件数量:"+files.size());
    }

修改效果:

修改前:

修改后:

  • 1
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值