这个工具类完成的工作如下:
1、第一个static方法,完成图片格式的转换。统一转换成.jpg格式。
package util; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferInt; import java.awt.image.DirectColorModel; import java.awt.image.PixelGrabber; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.File; /* * 处理图片的工具类: * 定义了3个方法 */ public class ImageUtil { //图片格式的转换,统一转换成.jpg格式 public static BufferedImage change2jpg(File f) { try { java.awt.Image i = Toolkit.getDefaultToolkit().createImage(f.getAbsolutePath()); PixelGrabber pg = new PixelGrabber(i, 0, 0, -1, -1, true); pg.grabPixels(); int width = pg.getWidth(), height = pg.getHeight(); final int[] RGB_MASKS = { 0xFF0000, 0xFF00, 0xFF }; final ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]); DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight()); WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null); BufferedImage img = new BufferedImage(RGB_OPAQUE, raster, false, null); return img; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } }
原文:https://www.cnblogs.com/Strugglinggirl/p/12927111.html