关于Java中的图像和文件处理的稍微冗长的问题

编辑:请不要将我的问题标记为重复或建议其他具有ImageIO库功能的问题。我在这里部分地试图了解图像本身的存储方式,以及如何编写自己的逻辑来检索和操作图像文件。

  1. I have a full red image I made using MS Paint (red = 255, blue = 0, green = 0)
  2. I read that image into a File object file
  3. Then I extracted the bytes using Files.readAllBytes(file.toPath()) into a byte array byteArray
  4. Now my expectation is that :

    a) byteArray[0], when converted to bitstream, should be all 1

    b) byteArray[1], when converted to bitstream, should be all 0

    c) byteArray[2], when converted to bitstream, should be all 0

因为据我了解,像素值以RGB顺序存储,每种颜色8位。

When I run my code, I don't get expected outcome. byteArray[0] is all 1 alright, but the other 2 aren't 0s.

我要去哪里错了?

编辑:根据要求,我包括图像大小,保存的格式和用于读取它的代码。

大小= 1920p x 1080p

格式= JPG

码:

        File file = new File("image_path.jpg");
        byte byteArray[]= new byte[(int) file.length()];
        try {
            byteArray = Files.readAllBytes(file.toPath());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int bits[] = new int[8];
        for(int j=0; j<8; j++)
        {
            bits[j] = (b[0] & (1 << j))==0 ? 0:1 ;
            //System.out.println("bitsb :"+bitsb[j]);
        }
评论
oqui
oqui

JPEG是一种复杂的图像格式。

它不保存原始图像像素数据,而是具有标头,可选的元数据和压缩的图像数据。

将其解压缩为原始像素值的算法非常复杂,但是有一些库可以为您完成工作。

Here is a short tutorial: https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

Here is the documentation of the BufferedImage class which will hold the image data: https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html

You will need to use one of the getRGB functions to access the raw pixel data. Make sure to check that your image is in 24 bit color format, if you want each color component to take 1 byte exactly!

JPEG支持其他格式,例如32位和16位!

Alternatively, save your image as 24 bit uncompressed BMP. The file will be much larger, but reading it is much simpler so you don't have to use a library. Just skip the header, then read raw bytes.

An even simpler image format to work with would be PBM/PPM.

点赞
评论