java 實現 圖片與byte 數組互相轉換


package webgate;
 
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
 
import javax.imageio.ImageIO;
 
//圖片文件,與 byte[] 互轉
public class TestFile {
 
	static byte[] bytes;
 
	public static void main(String[] args) throws Exception {
		File img = new File("W:\\img\\04.jpg");
		fileToByte(img);
		ByteToFile(bytes);
	}
 
	public static void fileToByte(File img) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			BufferedImage bi;
			bi = ImageIO.read(img);
			ImageIO.write(bi, "jpg", baos);
			bytes = baos.toByteArray();
			System.err.println(bytes.length);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			baos.close();
		}
	}
	
	static void ByteToFile(byte[] bytes)throws Exception{ 
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);   
        BufferedImage bi1 =ImageIO.read(bais); 
        try {   
            File w2 = new File("W:\\img\\00000000003.jpg");//可以是jpg,png,gif格式   
            ImageIO.write(bi1, "jpg", w2);//不管輸出什么格式圖片,此處不需改動   
        } catch (IOException e) {   
            e.printStackTrace();   
        }finally{
        	bais.close();
        }
    }  
 
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM