Autor Tema: Java convertir imagen en array de bytes Leer matriz de pixeles BMP, JPG, PNG...  (Leído 8929 veces)

Rop

  • Sin experiencia
  • *
  • APR2.COM
  • Mensajes: 1
    • Ver Perfil
Amigos: Para un proyecto de la universidad debo leer los siguientes datos de una imagen BMP:

* Ancho
* Alto
* Matriz de pixeles
* Rojo, Verde y Azul de cada pixel

Estas acciones debo poder realizarlas sin utilizar las clases: java.awt.Image (que incluye clases como BufferedImage), javax.imageIO, o la clase imageIO, por restricciones del proyecto no puedo utilizar estas clases.

He investigado y todas las formas que encuentro para hacer lo que necesito es utilizando las clases que tengo restringidas para este proyecto.

Alguno de ustedes me puede ayudar con esto?

Este es el código que tengo para leer byte por byte, pero tengo idea de como llegar a los bytes que tienen la información de los pixeles y sus colores RGB, una vez pueda obtener los colores RGB, lo que tengo que hacer es construir tres imágenes a partir de la imagen original, una formando pixeles con el valor en rojo encontrado en cada pixel, y cero en verde y azúl; lo mismo para crear una imagen solo de verde y otra solo de azúl.

Pero no se como encontrar el RGB leyendo cada byte.  Ya leí este artículo https://es.m.wikipedia.org/wiki/Windows_bitmap para ver el formato de un BMP, pero la verdad ya no sé como continuar.

Este es el código que llevo hasta el momento:

Código: [Seleccionar]
public void Build() {
        int contador=0;
        int aa = 0;

        try{
            FileInputStream archivo = new FileInputStream(mFile);
            BufferedInputStream buff = new BufferedInputStream(archivo);
            DataInputStream datos = new DataInputStream(buff);
            try{
                while (true){
                    for (int ii = 0; ii <= 17; ii++){
byte jj = datos.readByte();                   
                    }

                    int mAncho = datos.readInt();
                    int mAlto = datos.readInt();

                    if (aa == 0){
                    System.out.println("Ancho: " + mAncho + " - Alto: " + mAlto);
                    aa = 1;
                    }

/*                    System.out.printf("%d - %02X - %03d \n", contador++, in, in & 0xFF);
                    System.out.println(in);
                    Color color = new Color(in);

                    int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
int rgb = color.getRGB();

                    System.out.println("Rojo: " + red + " - Verde: " + green + " - Azul: " + blue + " - RGB: " + rgb);*/
            }
        }catch(EOFException eof){
                buff.close();
        }
        }catch(IOException e){
                System.out.println("Error  " + e.toString());
      }
}

De antemano agradezco todos los comentarios.
« Última modificación: 28 de Enero 2018, 14:42 por Ogramar »

Ogramar

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2660
    • Ver Perfil
Buenas, para escribir en los foros es conveniente seguir las reglas que se indican en https://www.aprenderaprogramar.com/foros/index.php?topic=1460.0

Parece ser que BufferedImage es la mejor forma para convertir una imagen en un array de bytes. No obstante, también habría otras maneras de hacerlo. Copio aquí el código que he encontrado de dos formas alternativas para ello por si pudiera servir de ayuda. El primer código sería equivalente al segundo, pero el segundo es mucho más compacto.

Código alternativa 1:

Código: [Seleccionar]
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
 
public class ConvertImage {
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
    /*
    * In this function the first part shows how to convert an image file to
    * byte array. The second part of the code shows how to change byte array
    * back to a image
    */
        File file = new File("C:\\rose.jpg");
        System.out.println(file.exists() + "!!");
 
        FileInputStream fis = new FileInputStream(file);
        //create FileInputStream which obtains input bytes from a file in a file system
        //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
 
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
                //no doubt here is 0
                /*Writes len bytes from the specified byte array starting at offset
                off to this byte array output stream.*/
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();
        //bytes is the ByteArray we need
 
 
        /*
         * The second part shows how to convert byte array back to an image file 
         */
 
 
        //Before is how to change ByteArray back to Image
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
        //ImageIO is a class containing static convenience methods for locating ImageReaders
        //and ImageWriters, and performing simple encoding and decoding.
 
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream, it seems file is OK
 
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        //Returns an ImageInputStream that will take its input from the given Object
 
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
 
        Image image = reader.read(0, param);
        //got an image file
 
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        //bufferedImage is the RenderedImage to be written
        Graphics2D g2 = bufferedImage.createGraphics();
        g2.drawImage(image, null, null);
        File imageFile = new File("C:\\newrose2.jpg");
        ImageIO.write(bufferedImage, "jpg", imageFile);
        //"jpg" is the format of the image
        //imageFile is the file to be written to.
 
        System.out.println(imageFile.getPath());
    }
}

Código alternativa 2:

Código: [Seleccionar]
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
 
 
public class SimpleConvertImage {
public static void main(String[] args) throws IOException{
String dirName="C:\\";
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
ImageIO.write(img, "jpg", baos);
baos.flush();
 
String base64String=Base64.encode(baos.toByteArray());
baos.close();
 
byte[] bytearray = Base64.decode(base64String);
 
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
}
}

Salu2

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".