您的位置:首页 > 其它

图片和字节之间的互相转换

2012-10-24 17:51 288 查看
package xiao.wei.test;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.imageio.ImageIO;

public class TestImage {
public static byte[] toByteArray(File imageFile) throws Exception {
BufferedImage img = ImageIO.read(imageFile);
ByteArrayOutputStream buf = new ByteArrayOutputStream((int) imageFile
.length());
try {
ImageIO.write(img, "jpg", buf);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return buf.toByteArray();
}

public static void main(String[] args) throws Exception {
byte[] b = toByteArray(new File("F:" + File.separator + "lol.jpg"));
ByteArrayInputStream in = new ByteArrayInputStream(b);
BufferedImage image = ImageIO.read(in);
File newFile = new File("d:" + File.separator + "lol.jpg");
ImageIO.write(image, "jpg", newFile);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: