2011-09-12 21 views
7

¿Hay un marco que pueda eliminar el espacio en blanco (rectangular) de una imagen? Creamos miniaturas de imágenes a partir de dibujos técnicos que, desafortunadamente, están en formato PDF. Convertimos el PDF a SVG y luego a JPG. A menudo, los dibujos técnicos son muy pequeñas y ahora se colocan en la esquina superior izquierda de la miniatura:Recortar/recortar un archivo JPG con espacio vacío con Java

+---------+----------------------+ 
|   |      | 
| (image) |      | 
|   |      | 
+---------+      | 
|        | 
|        | 
|        | 
|        | 
|    (empty space)  | 
|        | 
|        | 
+--------------------------------+ 

Entonces, ¿cómo puedo quitar fácilmente el espacio vacío y reducir el tamaño del archivo JPG?

+0

Hubiera pensado que era bastante fácil hacerlo con algunos bucles para comprobar que las filas/columnas completas fueran del mismo color. (O el color vacío) –

+5

BTW: la conversión de imágenes lineales a JPEG parece una mala elección. ¿Por qué no usar PNG? –

+2

¿Los archivos PDF también incluyen espacios en blanco o tienen el tamaño adecuado para el contenido? Si tienen el tamaño correcto, es posible que desee verificar cada paso de su canal de conversión si está descartando información sobre el tamaño. –

Respuesta

7

Se puede hacer en JAI como se demuestra en this thread. O aquí hay un código de Java que acabo de escribir que se puede utilizar para hacerlo:

public class TrimWhite { 
    private BufferedImage img; 

    public TrimWhite(File input) { 
     try { 
      img = ImageIO.read(input); 
     } catch (IOException e) { 
      throw new RuntimeException("Problem reading image", e); 
     } 
    } 

    public void trim() { 
     int width = getTrimmedWidth(); 
     int height = getTrimmedHeight(); 

     BufferedImage newImg = new BufferedImage(width, height, 
       BufferedImage.TYPE_INT_RGB); 
     Graphics g = newImg.createGraphics(); 
     g.drawImage(img, 0, 0, null); 
     img = newImg; 
    } 

    public void write(File f) { 
     try { 
      ImageIO.write(img, "bmp", f); 
     } catch (IOException e) { 
      throw new RuntimeException("Problem writing image", e); 
     } 
    } 

    private int getTrimmedWidth() { 
     int height  = this.img.getHeight(); 
     int width  = this.img.getWidth(); 
     int trimmedWidth = 0; 

     for(int i = 0; i < height; i++) { 
      for(int j = width - 1; j >= 0; j--) { 
       if(img.getRGB(j, i) != Color.WHITE.getRGB() && 
         j > trimmedWidth) { 
        trimmedWidth = j; 
        break; 
       } 
      } 
     } 

     return trimmedWidth; 
    } 

    private int getTrimmedHeight() { 
     int width   = this.img.getWidth(); 
     int height  = this.img.getHeight(); 
     int trimmedHeight = 0; 

     for(int i = 0; i < width; i++) { 
      for(int j = height - 1; j >= 0; j--) { 
       if(img.getRGB(i, j) != Color.WHITE.getRGB() && 
         j > trimmedHeight) { 
        trimmedHeight = j; 
        break; 
       } 
      } 
     } 

     return trimmedHeight; 
    } 

    public static void main(String[] args) { 
     TrimWhite trim = new TrimWhite(new File("...\\someInput.bmp")); 
     trim.trim(); 
     trim.write(new File("...\\someOutput.bmp")); 
    } 
} 
+0

¿Cómo podemos recortar con Color.TRANSLUCENT? –

6

Para los usuarios de Android, aquí hay un ejemplo usando Mike Kwan Respuesta:

public static Bitmap TrimImage(Bitmap bmp) { 
    int imgHeight = bmp.getHeight(); 
    int imgWidth = bmp.getWidth(); 

    //TRIM WIDTH 
    int widthStart = imgWidth; 
    int widthEnd = 0; 
    for(int i = 0; i < imgHeight; i++) { 
     for(int j = imgWidth - 1; j >= 0; j--) { 
      if(bmp.getPixel(j, i) != Color.TRANSPARENT && 
        j < widthStart) { 
       widthStart = j; 
      } 
      if(bmp.getPixel(j, i) != Color.TRANSPARENT && 
        j > widthEnd) { 
       widthEnd = j; 
       break; 
      } 
     } 
    } 
    //TRIM HEIGHT 
    int heightStart = imgHeight; 
    int heightEnd = 0; 
    for(int i = 0; i < imgWidth; i++) { 
     for(int j = imgHeight - 1; j >= 0; j--) { 
      if(bmp.getPixel(i, j) != Color.TRANSPARENT && 
        j < heightStart) { 
       heightStart = j; 
      } 
      if(bmp.getPixel(i, j) != Color.TRANSPARENT && 
        j > heightEnd) { 
       heightEnd = j; 
       break; 
      } 
     } 
    } 

    int finalWidth = widthEnd - widthStart; 
    int finalHeight = heightEnd - heightStart; 

    return Bitmap.createBitmap(bmp, widthStart,heightStart,finalWidth, finalHeight); 
} 

Esperanza esta ayuda a alguien :)

EDIT:

chicos, Acabo de actualizar mi respuesta primo último código se acaba de recortar el final de la imagen, no al principio. Este funciona muy bien :)

Cuestiones relacionadas