import java.awt.image.*;
import java.awt.*;
import java.io.*;
import javax.imageio.*;public class ImageByte { /**
* 转换Image数据为byte数组
*
* @param image
* Image对象
* @param format
* image格式字符串.如"jpeg","png"
* @return byte数组
*/
public static byte[] imageToBytes(BufferedImage image, String format) {
BufferedImage bImage = new BufferedImage(image.getWidth(null), image
.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics bg = bImage.getGraphics();
bg.drawImage(image, 0, 0, null);
bg.dispose(); ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(bImage, format, out);
} catch (IOException e) {
e.printStackTrace();
// Log.log(null,"imageToBytes(): " e);
}
return out.toByteArray();
} /**
* 转换byte数组为Image
*
* @param bytes
* Image的bytes数据数组
* @param filename
* 为要生成新的文件名
* @return boolean
*/
public static boolean ByteToImage(byte[] b, String filename) {
boolean bl = false;
File binaryFile = new File("e:\\test\\" + filename + ".gif");
try {
FileOutputStream fileOutStream = new FileOutputStream(binaryFile);
for (int i = 0; i < b.length; i++) {
fileOutStream.write(b[i]);
}
fileOutStream.flush();
bl = true;
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}// 创建文件输出流。
catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return bl;
} static byte[] b = null; public static void main(String args[]) { File file = new File("e:\\2.gif");
BufferedImage src;
try {
src = javax.imageio.ImageIO.read(file);
b = new ImageByte().imageToBytes(src, "jpeg");
System.out.println("b.length=======" + b.length);
// for(int i=0;i<b.length;i )
// {
// // System.out.println(b[i]);
// } // new ImageByte().bytesToImage(b);
} catch (IOException e) {
e.printStackTrace();
} // 构造Image对象
if (new ImageByte().ByteToImage(b, "2"))
System.out.println("文件从流中成功读出");
else
System.out.println("失败"); }}我将e:\\2.gif图片读到byte[] b变量里面,再将byte[] b变量数据输出生成e:\\test\\2.gif图片。可生成的e:\\test\\2.gif图片没有原来图片内容啊
解决方案 »
- 谁能推荐下开源的购物网站源码(struts+hibernate+spring)
- 急急急!高分跪求!Problem with ServiceSoap on LR 5.2 ExceptionInInitializerError
- 求一个清晰点的action jsp分页显示的方法。。。。。。。。。
- 在Hibernate中用什么工具将hbm.xml文件生成对应的pojo,怎么使用
- 请教:Jquery easyui 中的 treegrid 中是否允许多选?是否可以实现节点行拖动?
- jsp二级联动菜单
- jsp:include问题
- 请提供编写JSP/Servlet/JavaBean/EJB的几种服务器组合?
- jsp radio button
- 我想用在jsp中用jconnect连接sybase!不是如何下手
- 如何校对前后台验证码
- jsp中图片保存为文件
src = javax.imageio.ImageIO.read(file);
b = new ImageByte().imageToBytes(src, "jpeg"); --->"gif"
System.out.println("b.length=======" + b.length);
图片格式不同
src = javax.imageio.ImageIO.read(file);
b = new ImageByte().imageToBytes(src, "gif");
System.out.println("b.length=======" + b.length);
我是jdk1.6.0_06,jre1.6.0_06
你换成.jpg文件,测试一下看看