2013-04-17 9 views
16

Ich versuche, die Farbe für eine Reihe von Symbolen automatisch zu ändern. Jedes Symbol hat eine weiß gefüllte Ebene und der andere Teil ist transparent. Hier ist ein Beispiel: (in diesem Fall ist es grün ist, nur um es sichtbar)Ändern Sie die Farbe der nicht transparenten Teile von PNG in Java

icon search

Ich habe versucht, die folgendes zu tun:

private static BufferedImage colorImage(BufferedImage image) { 
     int width = image.getWidth(); 
     int height = image.getHeight(); 

     for (int xx = 0; xx < width; xx++) { 
      for (int yy = 0; yy < height; yy++) { 
       Color originalColor = new Color(image.getRGB(xx, yy)); 
       System.out.println(xx + "|" + yy + " color: " + originalColor.toString() + "alpha: " 
         + originalColor.getAlpha()); 
       if (originalColor.equals(Color.WHITE) && originalColor.getAlpha() == 255) { 
        image.setRGB(xx, yy, Color.BLUE.getRGB()); 
       } 
      } 
     } 
     return image; 
    } 

Das Problem, das ich ist, dass jedes Pixel haben ich bekomme den gleichen Wert hat:

32|18 color: java.awt.Color[r=255,g=255,b=255]alpha: 255 

Also mein Ergebnis ist nur ein farbiges Quadrat. Wie kann ich nur die Farbe der nicht transparenten Teile ändern? Und wieso haben alle Pixel sogar den gleichen Alpha-Wert? Ich denke, das ist mein Hauptproblem: Der Alpha-Wert wird nicht richtig gelesen.

Antwort

12

Das Problem ist, dass

Color originalColor = new Color(image.getRGB(xx, yy)); 

verwirft die alle Alpha-Werte. Stattdessen müssen Sie

Color originalColor = new Color(image.getRGB(xx, yy), true); 

verwenden, um Alpha-Werte verfügbar zu halten.

18

Warum es nicht funktioniert, ich weiß nicht, das wird.

Dies ändert alle pixles zu blau, ihre Alpha-Werte beibehalten ...

enter image description here

import java.awt.image.BufferedImage; 
import java.awt.image.WritableRaster; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 

public class TestColorReplace { 

    public static void main(String[] args) { 
     try { 
      BufferedImage img = colorImage(ImageIO.read(new File("NWvnS.png"))); 
      ImageIO.write(img, "png", new File("Test.png")); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

    private static BufferedImage colorImage(BufferedImage image) { 
     int width = image.getWidth(); 
     int height = image.getHeight(); 
     WritableRaster raster = image.getRaster(); 

     for (int xx = 0; xx < width; xx++) { 
      for (int yy = 0; yy < height; yy++) { 
       int[] pixels = raster.getPixel(xx, yy, (int[]) null); 
       pixels[0] = 0; 
       pixels[1] = 0; 
       pixels[2] = 255; 
       raster.setPixel(xx, yy, pixels); 
      } 
     } 
     return image; 
    } 
} 
+0

Vielen Dank für diese :) – 4ndro1d