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

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);
	}
}


 

你可能感兴趣的:(JAVA_Basis)