java-图片修改尺寸(缩小)

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;

public class ImageChange {

    public static void main(String[] args) throws IOException {

        // 缩小图片,输出base64字符串
        String imgPath = "/Users/pic/003.png";
        ImageChange.scaleImageAndEncodeToBase64(imgPath);

        // 缩小图片,导出新图
        String imagePath = "/Users/pic/002.png";
        String newImagePath = "/Users/pic/002-cp.png";
        ImageChange.FileSmall(imagePath, newImagePath);
        
    }

    public static String scaleImageAndEncodeToBase64(String imagePath) throws IOException {

        File imageFile = new File(imagePath);
        BufferedImage originalImage = ImageIO.read(imageFile);

        // 计算缩放比例
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        int targetWidth = width/3; // 设置新的宽度
        int targetHeight = (targetWidth * height) / width; // 计算新的高度

        // 创建新的图像
        BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);

        // 将BufferedImage转换为Base64
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(scaledImage, "png", outputStream); // 假设目标格式为jpg
        byte[] imageBytes = outputStream.toByteArray();
        String base64String = Base64.getEncoder().encodeToString(imageBytes);

        System.out.println("Successfully!");

        return base64String;
    }

    public static void FileSmall(String imgPath, String newImagePath){
        try {
            File file = new File(imgPath);
            BufferedImage image = ImageIO.read(file);

            // 计算缩放比例
            int width = image.getWidth();
            int height = image.getHeight();
            int newWidth = width/3; // 设置新的宽度
            int newHeight = (newWidth * height) / width; // 计算新的高度

            // 创建新的图像
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

            // 获取 Graphics 对象以进行绘制
            Graphics g = scaledImage.createGraphics();
            g.drawImage(image, 0, 0, newWidth, newHeight, null);
            g.dispose();

            ImageIO.write(scaledImage, "png", new File(newImagePath));

            System.out.println("Successfully!");

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值