package org.configurator.pdfgenerator.utils;
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;
import org.apache.xerces.impl.dv.util.Base64;
public class SimpleConvertImage {
public static void main(String[] args) throws IOException{
String dirName="D:\\";
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
BufferedImage img=ImageIO.read(new File(dirName,"plot.png"));
ImageIO.write(img, "png", baos);
baos.flush();
String base64String=Base64.encode(baos.toByteArray());
baos.close();
byte[] bytearray = Base64.decode(base64String);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
ImageIO.write(imag, "png", new File(dirName,"snap.png"));
}
}
Or Specific Functions
/***
* Image 2 Byte Array
* @param imageFile
* @return
* byte[]
*/
public static byte[] Image2Bytes(String imageFile){
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
BufferedImage img;
try {
img = ImageIO.read(new File(imageFile));
ImageIO.write(img, "png", baos);
baos.flush();
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String base64String=Base64.encode(baos.toByteArray());
return Base64.decode(base64String);
}
/****
* Byte Array to Image
* @param ImageBytesArray
* @param filePathName
* @return
* Image File
*/
public static File Bytes2Image(byte[] ImageBytesArray,String filePathName){
File imageFile = new File(filePathName);
try {
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(ImageBytesArray));
ImageIO.write(imag, "png", imageFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageFile;
}
Reference:
http://www.programcreek.com/2009/02/java-convert-image-to-byte-array-convert-byte-array-to-image/
http://stackoverflow.com/questions/3211156/how-to-convert-image-to-byte-array-in-java
0 comments:
Post a Comment