Pregunta

Tengo que crear una imagen BMP a partir de dos archivos TXT. El primero es una matriz MXN:

* * * * * * * *
Minnesota
C11 C21 .. CM1
...
C1N C2N .. CMN
* * * * * * * *

* * * * * * * *
6 5
.7 .7 .6 1.0 1.2 .1
.9 .3 .7 1.1 .7 .2
1 1.1 1.2 1.3 1.7 .6
.5 .6 .5 .4 .9 .1101
2 .1 .1 .1 2.1 1.1
* * * * * * * *

El segundo archivo txt es una escala de color, como esta

* * * * * * * *
Min1 Max1 R1 G1 B1
Min2 Max2 R2 G2 B2
...
minx maxx rx gx bx
* * * * * * * *

* * * * * * * *
0 .5 255 128 64
.5 .75 128 255 32
.75 1.25 64 64 225
01.50 5 128 128 0
* * * * * * * *

Así que tengo que leer de estos dos archivos. He intentado crear una matriz desde el primer archivo TXT usando la clase StringTokenizer, pero estoy perdido en absoluto. De los dos archivos tengo que crear una imagen BMP. ¿Alguien puede ayudarme de alguna manera?

¿Fue útil?

Solución

Suspiro ... Mientras escribía el programa, @jarnbjo explicó la misma idea. Pero aquí tienes algún código:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.NavigableMap;
import java.util.TreeMap;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageParser {
    public static void main(String[] args) {
        String dataContent = 
            "6 5\n" + 
            ".7 .7 .6 1.0 1.2 .1\n" + 
            ".9 .3 .7 1.1 .7 .2\n" + 
            "1 1.1 1.2 1.3 1.7 .6\n" + 
            ".5 .6 .5 .4 .9 .1101\n" + 
            "2 .1 .1 .1 2.1 1.1";

        String colorContent = 
            "0 .5 255 128 64\n" + 
            ".5 .75 128 255 32\n" + 
            ".75 1.25 64 64 225\n" + 
            "01.50 5 128 128 0";

        int width = 0;
        int height = 0;
        BufferedImage image = null;

        NavigableMap<Double, Integer> colorMap = new TreeMap<Double, Integer>();
        for (String colorLine : colorContent.split( "\n" )) {
            String[] colorValues = colorLine.split( " " );
            colorMap.put( Double.parseDouble( colorValues[1] ), 
                    Integer.parseInt( colorValues[2] ) << 16 | 
                    Integer.parseInt( colorValues[3] ) << 8 | 
                    Integer.parseInt( colorValues[4] ) );
        }
        boolean headerParsed = false;
        int y = 0;
        for( String dataLine : dataContent.split( "\n" ) ) {
            String[] dataArray = dataLine.split( " " );
            if( !headerParsed ) {
                width = Integer.parseInt( dataArray[ 0 ] );
                height = Integer.parseInt( dataArray[ 1 ] );
                image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
                headerParsed = true;
            }
            else {
                int x = 0;
                for( String data : dataArray ) {
                    Integer rgbValue = colorMap.higherEntry( Double.parseDouble( data ) ).getValue();
                    image.setRGB( x, y, rgbValue );
                    x++;
                }
                y++;
            }
        }

        JFrame frame = new JFrame();
        frame.getContentPane().add( new Viewer( image, width, height, 20 ) );
        frame.pack();
        frame.setVisible( true );
    }

    static class Viewer extends JPanel {
        Image m_image;
        int m_width;
        int m_height;
        int m_zoom;
        public Viewer( Image image, int width, int height, int zoom ) {
            m_image = image;
            m_width = width;
            m_height = height;
            m_zoom = zoom;
        }

        @Override
        public void paint(Graphics g) {
            g.drawImage( m_image, 0, 0, m_width * m_zoom, m_height * m_zoom, this );
        }
    };
}

Otros consejos

Si los rangos de color son continuos (su ejemplo le falta 1.25-1.5) y se garantiza que cubrirán todos los valores poseerios en el archivo de matriz, primero habría creado un TreeMap<Double, java.awt.Color>, usando el valor máximo del archivo de color como clave de mapa. Entonces puedes usar el TreeMap#ceilingEntry(K) Método para obtener el color para cualquier valor de matriz. Por ejemplo, si se pobla correctamente con los datos de sus pruebas, CeilingEntry (0.2) .getValue () devolverá el color (255,128,64).

En lugar de leer el archivo de matriz en una matriz, podría usar más fácilmente un directamente un java.awt.BufferedImage para atraer y luego usar javax.imageio.ImageIO para escribir la imagen buffed como un archivo BMP.

En el mismo mientras (necesito más tiempo jajaja) escribí solo el código para guardar en la matriz el primer archivo de matriz :( Aquí está el código solo si quieres echar un vistazo y funciona. Pero en realidad estoy en el tuyo . Te haré saber a lo que llegaré. Gracias chicos ...

import java.io.*;<br>
import java.util.StringTokenizer;

public class TokenizerUser4 {

public static double[][] matrix;

public static void main(String[] args) throws IOException {

    FileReader reader = new FileReader
        ("D:\\sonenos\\java\\FlussiIO\\new\\matrix.txt");       

    BufferedReader br = new BufferedReader(reader);

    String line;
    int rowIndex = 0;
    int counter = 0;
    int[] dim = new int[3]; 

    while ((line = br.readLine()) != null){

        counter++;

        if (counter == 1) {

            StringTokenizer dimensioni = new StringTokenizer(line);
            //int[] dim = new int[3];
            int i = 0;
            while(dimensioni.hasMoreTokens()){
                dim[i] = Integer.parseInt(dimensioni.nextToken());
                //System.out.println(dim[i] + " i=" + i);
                i++;

            }
            matrix = new double[dim[0]][dim[1]];
        }

        if (counter != 1){
            StringTokenizer theLine = new StringTokenizer(line);    

            int colIndex = 0;

            while (theLine.hasMoreTokens()){

                String st = theLine.nextToken();
                matrix[rowIndex][colIndex] = Double.parseDouble(st);

                colIndex = colIndex + 1;
            }

            rowIndex = rowIndex + 1;
        }               
    }

    for (int x = 0; x<dim[0];x++){
        for (int y = 0; y<dim[1]; y++){
            System.out.print(matrix[x][y] + " ");
        }
        System.out.println("\n");
    }

    br.close();     
}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top