Monday, September 24, 2007

How to Convert File to byte[] and Vice Versa.

Need of converting your image to byte[] and back to image again? No worries mate. Below are the methods to convert an image or file to byte[], and vice versa.

Note: If someone knows how to properly format below codes in a blog, please lemme know.

/*
* Created on 18-Sep-2007
*/
package com.taufek.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.imageio.stream.FileImageInputStream;

/**
* @author Taufek
*/
public class FileHandler {


public byte[] readImage2ByteArray() {
FileImageInputStream input = null;
ByteArrayOutputStream output = null;
byte[] buf = null;
byte[] data = null;
try {
input = new FileImageInputStream(new File("c:/dangdut.jpg"));
output = new ByteArrayOutputStream();
buf = new byte[512];
data = null;

int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}

data = output.toByteArray();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}

return data;
}

public void buildImageFromByteArray(byte[] data) {
InputStream is = null;
FileOutputStream fos = null;
byte[] buf = null;
int read = 0;
ByteArrayInputStream input = null;
try {

fos = new FileOutputStream(new File("c:/generated-dangdut.jpg"));
buf = new byte[512];

input = new ByteArrayInputStream(data);
while((read = input.read(buf)) != -1){
fos.write(buf, 0, read);
}

fos.flush();
fos.close();

} catch (Exception e) {
e.printStackTrace();
}
}

}

To My Perfect Angel

My wife has been so loving all these years. From the start, she luvs me for who I am. Don't mean to be so mushy, but you are my 'perfect human'. Having said that, I dedicate this song, 'Manusia Sempurna' to you my love.

Get this widget | Track details | eSnips Social DNA

Getting on the Bandwagon

Been avoiding blogging on the Net til' now. This is my , hmm..., can't really remember how many attempts I did previously, to start blogging. Little did I realized how our precious web had transformed so much recently. After attending a seminar on Web 2.0, I'd realized how important it is to join any community on the Net (Thanks to 'TigerFarm' from Sun). Hopefully, not so much of making money out of it, but works as a therapy by releasing some thoughts out of this brain of mine. Deep inside me, I know there must be something I could contribute to the world, at least in the geeky world of 'Java'.


System.out.println("Hello World");