Java 通过 ImageIO 转换图片分辨率以及图片类型

        今天有个杂活----- 将 6000 张图片将 jpg  转换为分辨率为 512x512 , 或者 256x256. 格式为jpeg .

可以通过 main 方法输入源文件夹路径,输出文件夹路径,直接输出

public static void main(String[] args) {
        //输入文件夹名称
        File folder = new File("E:\\sourcePath");
        File[] listFile = folder.listFiles();
        
            if (listFile != null) {
            //遍历
            for (File file : listFile) {
                if (file.isFile() && (file.getName().endsWith(".jpg") || file.getName().endsWith(".png"))) {
                  //记得修改文件的格式  例如我要转换 jpg 转换为 jpeg (那就是 0001.jpeg)                                  
                  //文件生成目录
                   String path = "E:\\targetPath\\" + file.getName().substring(0, file.getName().lastIndexOf(".")).jpeg;

                   changeImage(file.getAbsolutePath(), path, 512, 512);
                }
            }
        }
    }


private static void changeImage(String sourcePath, String targetPath, int targetWidth, int targetheight) {

        try {
            File inputFile = new File(sourcePath);
            BufferedImage inputImage = ImageIO.read(inputFile);

            // 获取文件的分辨率
            int inputWidth = inputImage.getWidth();
            int inputHeight = inputImage.getHeight();

            // 计算缩放比例
            double scaleX = (double) targetWidth / targetheight;
            double scaleY = (double) targetheight / targetWidth;
            double scale = Math.min(scaleX, scaleY);

            // 创建新的新的缩放后的图像,并居中
            int outWidth = (int) (inputWidth * scale);
            int outHeight = (int) (inputHeight * scale);
            BufferedImage outImage = new BufferedImage(targetWidth, targetheight, BufferedImage.TYPE_INT_ARGB);

            // 绘制缩放后的图像到新的图像中,并居中
            Graphics2D g2d = outImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(inputImage, (targetWidth - outWidth) / 2, (targetheight - outHeight) / 2, outWidth, outHeight, null);

            ImageIO.write(outImage, "jpeg", new File(targetPath));


            System.out.println("新文件存放于: " + targetPath+ "分辨率为" + targetWidth + "x" + targetheight);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

进行了一些修饰,这个接口可以将 bmp,jpg ,png ,jpeg 进行 图片格式转换 以及 图片分辨率格式输出.

输入参数如下:

@Data
@ApiModel("图片格式转换")
public class ChangeImage {

    @ApiModelProperty(value = "源文件夹路径", required = true)
    private String sourcePath;
    @ApiModelProperty(value = "生成文件夹路径", required = true)
    private String targetPath;
    @ApiModelProperty(value = "生成文件格式", required = true)
    private String targetType;
    @ApiModelProperty(value = "生成文件宽度", required = true)
    private int targetWidth;
    @ApiModelProperty(value = "生成文件高度", required = true)
    private int targetHeight;
    
}

通过接口调用:

package com.demo.controller;

import com.demo.config.Result;
import com.demo.enums.HttpStatus;
import com.demo.pojo.request.ChangeImage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Description Administrator
 * @Project_Name Demo
 * @Author admin
 * @Time 2024/8/13 13:25
 */

@RestController
@CrossOrigin
@Api(tags = "用于图片类型转换")
@RequestMapping("/changeImage")
public class ChangeImageController {


    public static String JPEG = "jpeg";
    public static String JPG = "jpg";
    public static String PNG = "png";
    public static String BMP = "bmp";

    @PostMapping("/readFile")
    @ApiOperation("读取文件夹进行图片转换.只能读取png,jpg")
    public Result readFile(@RequestBody ChangeImage changeImage) {
        String targetType = changeImage.getTargetType();
        if (PNG.equals(targetType) || JPG.equals(targetType) || BMP.equals(targetType) || JPEG.equals(targetType)) {
            File folder = new File(changeImage.getSourcePath());
            File[] listFile = folder.listFiles();
            if (listFile != null) {
                for (File file : listFile) {
                    if (file.isFile() && (file.getName().endsWith(".jpg") || file.getName().endsWith(".png") || file.getName().endsWith(".jpeg"))) {
                        //文件生成目录
                        String path = changeImage.getTargetPath() + "\\" + file.getName().substring(0, file.getName().lastIndexOf(".")) + "." + targetType;
                        changeImages(file.getAbsolutePath(), path, changeImage.getTargetWidth(), changeImage.getTargetHeight(), targetType);
                    }
                }
            }
            return Result.success();
        } else {
            return Result.error(HttpStatus.ERROR.code(), "仅支持 bmp,jpg ,png ,jpeg 文件转换格式");
        }
    }


    private static void changeImages(String sourcePath, String targetPath, int targetWidth, int targetheight, String targetType) {
        try {
            File inputFile = new File(sourcePath);
            BufferedImage inputImage = ImageIO.read(inputFile);

            BufferedImage outImage = new BufferedImage(targetWidth, targetheight, BufferedImage.TYPE_INT_RGB);

            if (!BMP.equals(targetType)) {

                // 获取文件的分辨率
                int inputWidth = inputImage.getWidth();
                int inputHeight = inputImage.getHeight();

                // 计算缩放比例
                double scaleX = (double) targetWidth / targetheight;
                double scaleY = (double) targetheight / targetWidth;
                double scale = Math.min(scaleX, scaleY);

                // 创建新的新的缩放后的图像,并居中
                int outWidth = (int) (inputWidth * scale);
                int outHeight = (int) (inputHeight * scale);

                // 绘制缩放后的图像到新的图像中,并居中
                Graphics2D g2d = outImage.createGraphics();
                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2d.drawImage(inputImage, (targetWidth - outWidth) / 2, (targetheight - outHeight) / 2, outWidth, outHeight, null);

            } else {
                // bmp不支持dpi  直接绘制bmp
                outImage.getGraphics().drawImage(inputImage.getScaledInstance(targetWidth, targetheight, Image.SCALE_SMOOTH), 0, 0, null);
            }

            boolean write = ImageIO.write(outImage, targetType, new File(targetPath));

            if (write) {
                System.out.println(" 新文件存放于: " + targetPath + ", 分辨率为:" + targetWidth + "  x  " + targetheight + "   .");
            } else {
                System.out.println(" 新文件生成失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

结束.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值