簡體   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