赞
踩
本文利用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);
参考链接:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。