This code will convert an image file to byte array and will write it into a binary file, and will read the binary file and converti it to image file.
import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedInputStream; import javax.imageio.ImageIO; public class conveter { /** * @param args */ public static void main(String[] args) { try { byte[] imageInByte; BufferedImage originalImage = ImageIO.read(new File( "Chrysanthemum.jpg")); // convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(originalImage, "jpg", baos); baos.flush(); imageInByte =baos.toByteArray(); baos.close(); write(imageInByte,"Chrysanthemum.jpg.bin"); // convert byte array back to BufferedImage InputStream in = new ByteArrayInputStream(read("Chrysanthemum.jpg.bin")); BufferedImage bImageFromConvert = ImageIO.read(in); ImageIO.write(bImageFromConvert, "jpg", new File( "Chrysanthemum.jpg.bin.jpg")); } catch (IOException e) { System.out.println(e.getMessage()); } } static byte[] read(String aInputFileName){ log("Reading in binary file named : " + aInputFileName); File file = new File(aInputFileName); log("File size: " + file.length()); byte[] result = new byte[(int)file.length()]; try { InputStream input = null; try { int totalBytesRead = 0; input = new BufferedInputStream(new FileInputStream(file)); while(totalBytesRead < result.length){ int bytesRemaining = result.length - totalBytesRead; //input.read() returns -1, 0, or more : int bytesRead = input.read(result, totalBytesRead, bytesRemaining); if (bytesRead > 0){ totalBytesRead = totalBytesRead + bytesRead; } } log("Num bytes read: " + totalBytesRead); } finally { log("Closing input stream."); input.close(); } } catch (FileNotFoundException ex) { log("File not found."); } catch (IOException ex) { log(ex); } return result; } static void write(byte[] aInput, String aOutputFileName){ log("Writing binary file..."); try { OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(aOutputFileName)); output.write(aInput); } finally { output.close(); } } catch(FileNotFoundException ex){ log("File not found."); } catch(IOException ex){ log(ex); } } private static void log(String string) { // TODO Auto-generated method stub } private static void log(IOException ex) { // TODO Auto-generated method stub } }
No comments:
Post a Comment
Thank you for Commenting Will reply soon ......