讀寫圖片檔案源碼,讀寫圖片源碼
package com.cqhope.read;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;/** * 操作圖片檔案類。 * @author yanghaitao */public class OpImage {public static void main(String[] args) {OpImage images = new OpImage();String fileName = "C:/Users/Administrator/Desktop/head/1407489615ttJB.jpg";byte[] bytes = images.readImage(fileName);System.out.print(bytes.length);images.outImage(bytes, "C:/Users/Administrator/Desktop/123.jpg", "jpg");}/** * 輸入圖片檔案。 * @param fileName 圖片檔案全路徑 * @return 返回圖片資料 */public byte[] readImage(String fileName){byte[] bytes = null;File f = new File(fileName);BufferedImage bi = null;ByteArrayOutputStream baos = null;try {bi = ImageIO.read(f);baos = new ByteArrayOutputStream();ImageIO.write(bi, "jpg", baos);bytes = baos.toByteArray();} catch (IOException e) {e.printStackTrace();}finally {if(baos != null){try {baos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return bytes;}/** * 輸出圖片檔案。 * @param bytes 圖片資料 * @param fileName 輸出檔案名 * @param type 輸出檔案類型 * @throws IOException */public void outImage(byte[] bytes, String fileName, String type){//設定預設檔案格式。if(type == null || "".equals(type)) {type = "jpg";}try { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage bi1 =ImageIO.read(bais); File w2 = new File(fileName); ImageIO.write(bi1, type, w2);}catch(Exception e) {e.printStackTrace();}}}