当前位置:   article > 正文

Java实现图片格式转换_java 将jpg格式的图片转jpeg

java 将jpg格式的图片转jpeg

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

代码实现如下:

  1. import javax.imageio.ImageIO;
  2. import java.awt.*;
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.ByteArrayOutputStream;
  7. public class ResizeImageExample {
  8. public static void main(String... args) throws IOException {
  9. File input = new File("ss-2.png");
  10. BufferedImage image = ImageIO.read(input);
  11. BufferedImage resized = resizebyaspect(image, 1655, 2340);
  12. File output = new File("ss-2-resized-500x500.png");
  13. ImageIO.write(resized, "png", output);
  14. }
  15.     // 不按比例缩放
  16. private static BufferedImage resize(BufferedImage img, int height, int width) {
  17. Image tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
  18. BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  19. Graphics2D g2d = resized.createGraphics();
  20. g2d.drawImage(tmp, 0, 0, null);
  21. g2d.dispose();
  22. return resized;
  23. }
  24.     // 按比例缩放
  25. private static BufferedImage resizebyaspect(BufferedImage img, int height, int width) {
  26. int ori_width = img.getWidth();
  27. int ori_height = img.getHeight();
  28. float ratio_w = (float)width/ori_width;
  29. float ratio_h = (float)height/ori_height;
  30. int new_width = (ratio_w < ratio_h) ? width : (int)(ratio_h * ori_width);
  31. int new_height = (ratio_h < ratio_w) ? height : (int)(ratio_w * ori_height);
  32. System.out.println(new_height);
  33. System.out.println(new_width);
  34. Image tmp = img.getScaledInstance(new_width, new_height, Image.SCALE_SMOOTH);
  35. BufferedImage resized = new BufferedImage(new_width, new_height, BufferedImage.TYPE_INT_ARGB);
  36. Graphics2D g2d = resized.createGraphics();
  37. g2d.drawImage(tmp, 0, 0, null);
  38. g2d.dispose();
  39. return resized;
  40. }
  41. }

说明:

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/715976
推荐阅读
相关标签
  

闽ICP备14008679号