码迷,mamicode.com
首页 > 其他好文 > 详细

读写图片文件源码

时间:2015-06-21 02:06:00      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:读写图片文件

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 block
					e.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();
		}
	}
}

读写图片文件源码

标签:读写图片文件

原文地址:http://blog.csdn.net/yanghaitaohhh/article/details/46575877

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!