繁体   English   中英

如何在Java中将图像转换为像素?

[英]How to convert image into pixels in java?

我有JPEG的RGB图像。 我想将此图像转换为像素并显示在文本文件中。 这个怎么做?

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;
}

如何将此信息存储在文本文件中作为序列矢量格式?

您可以将整数保存为逗号分隔的列表。

确保还保存图像宽度,以便可以还原图像。

使用类似以下的内容。 希望这会有所帮助

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
        }
    }
}

您可以考虑自己的算法来读取文本文件并检索数据。 :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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