Search code examples
javaimageraster

Change only rgb values of image and convert back to image


I need to convert my image .bmp or .jpg to byte[], change some values rgb, convert it back to image and see a difference - some wrong pixels on my image.

I tried doing it just by converting image to byte[] changing it and converting back, but by changing random values I get a corrupted image.

So ,how do I access only the changeable values of my image?

Started with this but not sure where to do next:

    File file = new File("image.jpg");
    BufferedImage bufferedImage = ImageIO.read(file);
    WritableRaster raster = bufferedImage.getRaster();
    DataBufferByte data = (DataBufferByte) raster.getDataBuffer();

   byte[] pixels = data.getData();

Would appreciate any help.


Solution

  • Found a solution. To convert regb values of .bmp image to binary vector that I need to change I applied this solution:

    public String imageToVector(BufferedImage image) throws Exception {
            String vectorInString = "";
            for (int x = 0; x < image.getWidth(); x++) {
                for (int y = 0; y < image.getHeight(); y++) {
                    Color color = new Color(image.getRGB(x, y), false);
                vectorInString = vectorInString.concat(decimalToBinary(color.getRed()));
                vectorInString = vectorInString.concat(decimalToBinary(color.getGreen())); 
                vectorInString = vectorInString.concat(decimalToBinary(color.getBlue())); 
                }
            }
            return vectorInString;
    }