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();
}
}
}
读写图片文件源码
最新推荐文章于 2022-10-09 19:43:14 发布