简体   繁体   中英

How to convert image into pixels in java?

I have RGB image in JPEG. I want to convert this image into pixels and to be displayed in a text file. How to do this?

public static int[][][] getPixelData(Image image) {

    // get Image pixels in 1D int array
    int width = image.getWidth(null);
    int height = image.getHeight(null);

    int[] imgDataOneD = imageToPixels(image);

private static int[] imageToPixels(Image image) {

    int height = image.getHeight(null);
    int width = image.getWidth(null);

    int pixels[] = new int[width * height];

    PixelGrabber grabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);

    try {
        grabber.grabPixels();
    } catch (InterruptedException e) {
    }

    return pixels;
}

How to store this information in a text files as sequence vector format?

You could just save the integers as a comma separated list.

make sure to also save the image width, so you can restore the image.

Use something like following. Hope this will help

import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class ImageToText {
    public static void main(String args[]) throws IOException {
        File file = new File("your file path.jpg");
        BufferedImage image = ImageIO.read(file);
        // Getting pixel color by position x=100 and y=40

        for (int i = 0; i < image.getHeight(); i++) {
            for (int j = 0; j < image.getWidth(); j++) {
                int color = image.getRGB(j, i);

                // You can convert the colour to a readable format by changing
                // to following string. It is a 6 character hex
                // String clr = Integer.toHexString(color).substring(2);

                // Write this int value or string value to the text file
                // Add a comma or any other separator. Since it is always 6
                // characters long you can avoid using comma. It will save some
                // space.
            }
            // add a new line
        }
    }
}

You can think about your own algo to read the text file and retrieve the data. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM