2013-03-13 4 views
0

У меня есть изображение RGB в формате JPEG. Я хочу преобразовать это изображение в пиксели и отображаться в текстовом файле. Как это сделать?Как преобразовать изображение в пиксели в java?

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

Как сохранить эту информацию в текстовых файлах как векторный формат последовательности?

+0

какой фрагмент данных вы хотите сохранить int [], int [] [] или int [] [] []? – phoenix7360

+0

Показать его в текстовом файле? Что, значения RGB сливаются вместе? – Zutty

ответ

0

Используйте что-то вроде следующего. Надеюсь, это поможет

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

Вы можете подумать о своем собственном алго, чтобы прочитать текстовый файл и получить данные. :-)

0

Вы можете просто сохранить целые числа в виде списка, разделенного запятой.

Обязательно сохраните ширину изображения, чтобы можно было восстановить изображение.

Смежные вопросы