Skip to content

Instantly share code, notes, and snippets.

@gedankennebel
Last active December 23, 2015 08:09
Show Gist options
  • Save gedankennebel/6605932 to your computer and use it in GitHub Desktop.
Save gedankennebel/6605932 to your computer and use it in GitHub Desktop.
Convert an image from file to byte[]
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* User: najum
* Date: 01.08.12
* Time: 12:51
*/
public class ImageToByteArray {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
File file = new File("/Users/najum/Desktop/test.png");
loadFileFromPersistentStore(file);
BufferedImage bufferedImage = ImageIO.read(file);
loadImageFromMemory(bufferedImage);
}
/**
* @param file
* @throws IOException
*/
private static void loadImageFromMemory(BufferedImage image) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", byteArrayOutputStream);
byte[] imageData = byteArrayOutputStream.toByteArray();
System.out.println(imageData.length);
}
/**
* @throws Exception
* @throws FileNotFoundException
*/
private static void loadFileFromPersistentStore(File file) throws Exception, FileNotFoundException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
copyStream(new FileInputStream(file), byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
System.out.println(data.length);
}
private static void copyStream(InputStream src, OutputStream dest) throws Exception {
byte[] buffer = new byte[16384];
int len;
while ((len = src.read(buffer)) > 0) {
dest.write(buffer, 0, len);
}
src.close();
dest.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment