2013-04-17 16 views
16

Bir simge grubunun rengini otomatik olarak değiştirmeye çalışıyorum. Her simgenin beyaz dolu bir tabakası ve diğer kısmı saydamdır.Png'nin saydam olmayan parçalarının rengini değiştirme Java'da

icon search

aşağıdaki yapmaya çalıştım (sadece görünür hale getirmek için bu yeşil bu durumda):

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

Ben sorun her pikselde olmasıdır İşte bir örnek Ben de aynı değere sahibiz:

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

Sonuçta yalnızca renkli bir kare var. Yalnızca saydam olmayan parçaların rengini değiştirmek için nasıl yapabilirim? Ve neden, tüm piksellerin aynı alfa değerine sahip olması neden? Sanırım bu benim asıl sorunum: Alfa değerinin doğru okunmadığı.

cevap

12

problem,

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

atar bütün alfa değerleri. Bunun yerine, alfa değerlerini kullanılabilir tutmak için

'u kullanmanız gerekir.

18

Neden çalışmıyor, bilmiyorum, bu olacak.

Bu

... onların alfa değerlerini koruyarak, bu :) için

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

Teşekkür mavi tüm pixles değiştirir – 4ndro1d

İlgili konular