Creating 8 bit image from byte array

前端 未结 3 1373
深忆病人
深忆病人 2021-01-23 07:02

The byte array is obtained this way -

BufferedImage image = new Robot().createScreenCapture(new Rectangle(screenDimension));
byte[] array = ((DataBufferByte)getG         


        
相关标签:
3条回答
  • 2021-01-23 07:14

    You have to specify the correct ColorSpace corresponding to a grayscale image.

    Here's an example, as found on http://technojeeves.com/joomla/index.php/free/89-create-grayscale-image-on-the-fly-in-java:

    public static BufferedImage getGrayscale(int width, byte[] buffer) {
        int height = buffer.length / width;
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
        int[] nBits = { 8 };
        ColorModel cm = new ComponentColorModel(cs, nBits, false, true,
                Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
        SampleModel sm = cm.createCompatibleSampleModel(width, height);
        DataBufferByte db = new DataBufferByte(buffer, width * height);
        WritableRaster raster = Raster.createWritableRaster(sm, db, null);
        BufferedImage result = new BufferedImage(cm, raster, false, null);
    
        return result;
    }
    
    0 讨论(0)
  • 2021-01-23 07:16

    I hope it'll help you if I explain to you how to convert from ARGB/RGB 2 gray cause there are too many unknown functions and classes :P

    ARGB is 32 bit/pixel so 8 bit for every channel. the alpha channel is the opacity so the opposite of transparency so 0 is transparent.

    RGB is 24 bit/pixel. to convert from ARGB to RGB you have to dismiss the alpha channel.

    to convert from RGB to grayscale u have to use this formula:

    0.2989 * R + 0.5870 * G + 0.1140 * B
    

    so you have to figure out which byte belongs to which channel ;)

    0 讨论(0)
  • 2021-01-23 07:18

    This will work. Just make sure you tweak the image type the way you need:

    Image img = new ImageIcon(array).getImage();
    BufferedImage image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    image.createGraphics().drawImage(img, 0, 0, null);
    
    0 讨论(0)
提交回复
热议问题