public static byte[] formatImgJPEG(InputStream is) throws IOException {
Image img = ImageIO.read(is);
int wid = img.getWidth(null);
int hei = img.getHeight(null);
BufferedImage bi = new BufferedImage(wid, hei,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
Image image = img.getScaledInstance(wid, hei, Image.SCALE_DEFAULT);
//Color.WHITE:把透明背景绘制成白色,如果不写,默认是黑色
g2d.drawImage(image, 0, 0, wid, hei,Color.WHITE, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", out);
byte[] bytes = out.toByteArray();
out.close();
return bytes;
}
以下是一些File,Image,byte[],inputStream之间的转换
public static byte[] getFileBuffer(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[256 * 1024];
byte[] fileBuffer = new byte[(int) file.length()];
int count = 0;
int length = 0;
while ((length = fis.read(buffer)) != -1) {
for (int i = 0; i
fileBuffer[count + i] = buffer[i];
}
count += length;
}
return fileBuffer;
}
public static InputStream BytesToInputStream(byte[] bytes) {
InputStream iStream = new ByteArrayInputStream(bytes);
return iStream;
}
public static Image bytesToImage(byte[] bytes) throws IOException {
InputStream is = BytesToInputStream(bytes);
Image image = ImageIO.read(is);
return image;
}