BufferedImage byte数组转换

import java.io.ByteArrayOutputStream;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.io.IOException;

public static byte[] bufferedImageToByteArray(BufferedImage img)
			throws ImageFormatException, IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
		encoder.encode(img);
		return os.toByteArray();
	}

 

 

import java.io.IOException;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;

public static byte[] bufferedImage2ByteArray(BufferedImage image) throws IOException{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(image, "jpeg", baos);
		return baos.toByteArray();
	}

 

public static byte[] bufferedImage2ByteArrayByFile(BufferedImage image)
			throws Exception {
		DataInputStream dis = null;
		FileInputStream fis = null;
		FileOutputStream fos = null;
		byte[] buf = null;
		File file = null;
		file = new File("D:/tmp.jpg");
		fos = new FileOutputStream(file);
		ImageIO.write(image, "jpeg", fos);
		fos.close();
		fis = new FileInputStream(file);
		dis = new DataInputStream(fis);
		buf = new byte[dis.available()];
		dis.read(buf); 
		dis.close();
		fis.close();
		file.delete();
		return buf;
	}
必须要先关闭文件输入、输出流才能删除临时文件。(78ms)

 

第一种方法效率高 

你可能感兴趣的:(java,OS,sun)