Question

I'm working on a simple image program where the user can alter the HSB values of an image. However, when I change the HSB values of an images and convert back to RGB, it seems to lose it's transparency or alpha values (it goes black where the transparency is). Here's what I have below (I've put the relevant parts together):

public static BufferedImage getEnhancedImagesHSB(BufferedImage image, float[] hsbOrg)
{

  int height = image.getHeight();
  int width = image.getWidth();

  float[] hsb = new float[]{0,0,0,0};
  int[] originalPixels = image.getRGB(0,0, width, height, null, 0, width);
  int[] enhancedImagePixels = image.getRGB(0,0, width, height, null, 0, width);

  for (int i = 0; i < originalPixels.length; i++)
  {
    Color c = new Color( originalPixels[i]);
    int red =c.getRed();
    int green = c.getGreen();
    int blue = c.getBlue();

    hsb = Color.RGBtoHSB(red, green, blue, hsb);

    hsb[ 3 ] = c.getAlpha() / 255f;

     hsb[0] = (float)(hsb[0] +( hsbOrg[0]/360.0));//hue

    hsb[1] *=  (hsbOrg[1]/100);
      if(hsb[1] > 1.0)
          hsb[1] = (float)0.9;


    hsb[2] *=  (hsbOrg[2]/100);
      if(hsb[2] > 1.0) 
          {hsb[2] = (float)0.9;}

    enhancedImagePixels[i] = Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]);
  }


  BufferedImage newImage = new BufferedImage(width, height,    BufferedImage.TYPE_INT_ARGB  );  
  newImage.setRGB(0, 0, width, height, enhancedImagePixels, 0, width);

  return newImage;
}

According to the docs getRGB(), setRGB() use the default RGB color model (TYPE_INT_ARGB) so the alpha values should be preserved. But changing the images HSB values results in the new buffered image having a black color where the transparency should be. How can I edit the images HSB values and then create a new image without losing the images transparency?

Edit: Below is an image from before and after some random Hue, saturation and brightness has been applied. As you can see, the image has lost its transparency. enter image description here

Was it helpful?

Solution

Color c2 = Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]);
enhancedImagePixels[i] = new Color(c2.getRed(), c2.getGreen(), c2.getBlue(),
        c.getAlpha());

Which is ugly. There seems to be no conversion for hsb[3] (alpha). Using a image.getAlphaRaster() might be the solution.

OTHER TIPS

Thanks to Joop Eggen for pointing me into the right direction. I wrote directly into the image raster (using setPixel()) the adjusted Hue, saturation, brightness and alpha values. Below is a great article discussing the subject matter.

Article.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top