how to convert image to byte array in java? [dupli

2019-01-02 18:06发布

This question already has an answer here:

I want to convert an image to byte array and vice versa. Here, the user will enter the name of the image (.jpg) and program will read it from the file and will convert it to a byte array.

9条回答
唯独是你
2楼-- · 2019-01-02 18:45

Try this code snippet

BufferedImage image = ImageIO.read(new File("filename.jpg"));

// Process image

ImageIO.write(image, "jpg", new File("output.jpg"));
查看更多
泛滥B
3楼-- · 2019-01-02 18:47

Here is a complete version of code for doing this. I have tested it. The BufferedImage and Base64 class do the trick mainly. Also some parameter needs to be set correctly.

public class SimpleConvertImage {
    public static void main(String[] args) throws IOException{
        String dirName="C:\\";
        ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
        BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
        ImageIO.write(img, "jpg", baos);
        baos.flush();

        String base64String=Base64.encode(baos.toByteArray());
        baos.close();

        byte[] bytearray = Base64.decode(base64String);

        BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
        ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    }
}

Reference link

查看更多
与风俱净
4楼-- · 2019-01-02 18:49

Check out javax.imageio, especially ImageReader and ImageWriter as an abstraction for reading and writing image files.

BufferedImage.getRGB(int x, int y) than allows you to get RGB values on the given pixel, which can be chunked into bytes.

Note: I think you don't want to read the raw bytes, because then you have to deal with all the compression/decompression.

查看更多
登录 后发表回答