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();
}
}

}

2 comments:

Unknown said...

Have you tried >pre%lt; tags around the code block?

Unknown said...

Heh, having my own formatting issues.

Lets try again! Have you tried <pre> tags?