Java实现图片格式转换

本文利用java实现将jpg tiff png格式的图片统一转换为png或tiff或jpg的图片,在转换的时候会做图像的resize:

代码实现如下:

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

public class ResizeImageExample {

    public static void main(String... args) throws IOException {
        File input = new File("ss-2.png");
        BufferedImage image = ImageIO.read(input);
        BufferedImage resized = resizebyaspect(image, 1655, 2340);
        File output = new File("ss-2-resized-500x500.png");
        ImageIO.write(resized, "png", output);
    }
    // 不按比例缩放
    private static BufferedImage resize(BufferedImage img, int height, int width) {
        Image tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resized.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();
        return resized;
    }
    // 按比例缩放
    private static BufferedImage resizebyaspect(BufferedImage img, int height, int width) {
        int ori_width = img.getWidth();
        int ori_height = img.getHeight();
        float ratio_w = (float)width/ori_width;
        float ratio_h = (float)height/ori_height;
        int new_width = (ratio_w < ratio_h) ? width : (int)(ratio_h * ori_width);
        int new_height = (ratio_h < ratio_w) ? height : (int)(ratio_w * ori_height);
        System.out.println(new_height);
        System.out.println(new_width);
        Image tmp = img.getScaledInstance(new_width, new_height, Image.SCALE_SMOOTH);
        BufferedImage resized = new BufferedImage(new_width, new_height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resized.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();
        return resized;
    }
}

说明:

1. 输入的图片可以是各种格式

2. 输出的图片也可以是各种格式, 不同的格式修改下面的"png",为"jpg"或其他

ImageIO.write(resized, "png", output);

参考链接:

1. Image transcoding (JPEG to PNG) with Java

2. Java Resize Image to Fixed Width and Height Example

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值