JAVA中实现图片对象转换成图片文件和字节数组(Byte[ ])的方法讨论
JAVA中实现图片对象转换成图片文件和字节数组(Byte[ ])的方法讨论
网上关于这方面的讨论其实有很多,但找起来也不太容易,笔者以JMSL4.0画出的chart对象为例阐释这一过程,希望能带来些启发。
import com.imsl.chart.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
public class SampleImageIO {
public byte[] getByteArray() {
byte[] b = null;
try{
Chart chart = createChart();//generate image
chart.setScreenSize(new java.awt.Dimension(500,500));
BufferedImage bi = new BufferedImage(500, 500, BufferedImage.TYPE_4BYTE_ABGR_PRE);
chart.paintChart(bi.createGraphics()); //generate buffered image
//感觉bufferedimage经常和imageIO成对出现作为对图像对象的标准转化形式。
File file = new File("D:\\workspace\\SampleImageIO1.png");//deploy file
javax.imageio.ImageIO.write(bi, "PNG", file);//generate file
ByteArrayOutputStream bos = new ByteArrayOutputStream();
javax.imageio.ImageIO.write(bi, "png", bos);
b = bos.toByteArray();//generate byte[]
//check to get the byte[]
//其实byte[]的最大的用途应该是网站的图片动态显示,下面的code只是实验一下,也顺便介绍一下byte[]转换成文件的操作。
String newFileName = "d:\\temp\\wine1.png";
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(b, 0, b.length);
imageOutput.close();
System.out.println("Please find image in " + newFileName);
}
catch(Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
return b;
}
//jmsl画图的code,挺快的,好用,但是人家是收费的library~~,抛砖引玉吧
static Chart createChart() {
Chart chart = new Chart();
AxisXY axis = new AxisXY(chart);
int npoints = 20;
double dx = .5 * Math.PI/(npoints-1);
double x[] = new double[npoints];
double y[] = new double[npoints];
// Generate some data
for (int i = 0; i < npoints; i++){
x[i] = i * dx;
y[i] = Math.cos(x[i]);
}
new Data(axis, x, y);
return chart;