How to Convert Image to Byte Array in Java

how to convert image to byte array in java?

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);

// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();

return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

About convert Image to byte[] and reverse in Java

Let's start with the paint code.

ImageIO.read(in) is expecting a valid image format that one of it's pluggable service provides knows how to read and convert to a BufferedImage.

When you pass the byes from extractBytes, you're simply passing back an array of bytes that represents the actual image file. I'd be the same as saying Image.read(new File("image/pikachu.png"))

However, the data buffer returned from your extractBytes2 is returning a internal representation of the image data, which may not be "readable" by ImageIO.

UPDATED

A BufferedImage is an accessible buffer of image data, essentially
pixels, and their RGB colors. The BufferedImage provides a powerful
way to manipulate the Image data. A BufferedImage object is made up of
two parts a ColorModel object and a Raster object.

Sample Image

Referenced from here

UPDATED

I had this wacky idea on the way home of how to convert a BufferedImage to a byte array...

The basic idea is to use ImageIO.write to write out the BufferedImage to a ByteOutputStream...

public static byte[] extractBytes2(String ImageName) throws IOException {
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);

ByteOutputStream bos = null;
try {
bos = new ByteOutputStream();
ImageIO.write(bufferedImage, "png", bos);
} finally {
try {
bos.close();
} catch (Exception e) {
}
}

return bos == null ? null : bos.getBytes();

}

Here's my test...

Sample Image

public class TestByteImage {

public static void main(String[] args) {
new TestByteImage();
}

public static byte[] extractBytes2(String ImageName) throws IOException {
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);

ByteOutputStream bos = null;
try {
bos = new ByteOutputStream();
ImageIO.write(bufferedImage, "png", bos);
} finally {
try {
bos.close();
} catch (Exception e) {
}
}

return bos == null ? null : bos.getBytes();

}

public TestByteImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class ImagePane extends JPanel {

private BufferedImage original;
private byte[] byteData;
private BufferedImage fromBytes;

public ImagePane() {
String name = "/path/to/your/image";
try {
original = ImageIO.read(new File(name));
byteData = extractBytes2(name);
} catch (IOException ex) {
ex.printStackTrace();
}

setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48f));

}

@Override
public Dimension getPreferredSize() {
return original == null ? super.getPreferredSize() : new Dimension(original.getWidth() * 2, original.getHeight());
}

protected void drawText(Graphics2D g2d, String text, int x, int width) {
BufferedImage img = new BufferedImage(width, getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D tmpg = img.createGraphics();
tmpg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
tmpg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
tmpg.setFont(g2d.getFont());
tmpg.setColor(Color.RED);
FontMetrics fm = tmpg.getFontMetrics();
int xPos = ((width - fm.stringWidth(text)) / 2);
int yPos = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
tmpg.drawString(text, xPos, yPos);
tmpg.dispose();

AffineTransform transform = g2d.getTransform();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(-10), x + (x + width) / 2, getHeight() / 2));
g2d.drawImage(img, x, 0, this);
g2d.setTransform(transform);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (original != null) {
g.drawImage(original, 0, 0, this);
drawText((Graphics2D) g, "Original", 0, original.getWidth());
}
if (byteData != null && fromBytes == null) {
try {
fromBytes = ImageIO.read(new ByteInputStream(byteData, byteData.length));
} catch (IOException exp) {
exp.printStackTrace();
}
}
if (fromBytes != null) {
g.drawImage(fromBytes, getWidth() - fromBytes.getWidth(), 0, this);
drawText((Graphics2D) g, "From Bytes", getWidth() - fromBytes.getWidth(), fromBytes.getWidth());
}
}
}
}

Image conversion to byte array in Java

First to get byte array of image you need to convert image to BufferedImage. See ths link to convert image to BuffredImage. http://www.dzone.com/snippets/converting-images

After you get BufferedImage convert t into bytearray using bufferedImageToByteArray function.

BufferedImage buf_image; // this is BufferedImage reference you got after converting it from Image
byte[] imageByteArray = bufferedImageToByteArray(buf_image,"jpg");

public static byte[] bufferedImageToByteArray(BufferedImage image, String format) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, format, baos);
return baos.toByteArray();
}

Write an image from project resources to the byte array

I suggest do the following:

Use commons IO, then:

InputStream is = getClass().getResourceAsStream("/icons/default_image.png")
byte[] bytes = IOUtils.toByteArray(is);

(try and catch the exceptions.)

Edit As of Java 9 no Library needed:

InputStream is = getClass().getResourceAsStream("/icons/default_image.png")
byte[] bytes = is.readAllBytes();

(Again try and catch the exceptions.)

Convert image to byte array quickly

In getImageBytes() you are compressing the image to PNG which can take time. The fastest ImageIO.write call you can achieve is

ImageIO.write(copyImage(image), "bmp", baos);

where there is no compression. Still, ImageIO contains reference implementations of image formats which are not designed for speed.



Related Topics



Leave a reply



Submit