Java Graphics Draw draw(int[] pixels, int width, int height)

Here you can find the source of draw(int[] pixels, int width, int height)

Description

http://stackoverflow.com/questions/4386446/problem-using-imageio-write-jpg-file/4388542#4388542 <p> I needed to make all this stuff with RGB masks and the color model because otherwise pixels wouldn't get drawn correctly.

License

Open Source License

Parameter

Parameter Description
pixels the pixels.
width width.
height height.

Return

a buffered image created from the pixel array.

Declaration

public static BufferedImage draw(int[] pixels, int width, int height) 

Method Source Code

//package com.java2s;
/*// ww  w . j  a  v  a2 s. c om
  This file is part of Cuber.
    
Cuber is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
Cuber is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with Cuber.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;

import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;

import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class Main {
    private static final int[] RGB_MASKS = { 0xFF0000, 0xFF00, 0xFF };
    private static final ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);

    /**
     * http://stackoverflow.com/questions/4386446/problem-using-imageio-write-jpg-file/4388542#4388542
     * <p>
     * I needed to make all this stuff with RGB masks and the color model because otherwise pixels wouldn't
     * get drawn correctly.
     * 
     * @param pixels
     *            the pixels.
     * @param width
     *            width.
     * @param height
     *            height.
     * @return a buffered image created from the pixel array.
     * @since 25/06/2013
     * @author wonka
     */
    public static BufferedImage draw(int[] pixels, int width, int height) {
        DataBuffer buffer = new DataBufferInt(pixels, width * height);
        WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null);
        BufferedImage image = new BufferedImage(RGB_OPAQUE, raster, false, null);
        return image;
    }
}

Related

  1. drawAndFill(Graphics g, Shape s, Color draw, Color fill)
  2. drawAngledLine(Graphics g, int x, int y, double angle, int length)
  3. drawAt(final Graphics2D g, final double x, final double y, final Shape s)
  4. drawAutoCompleteMarker(Graphics2D g2, int x, int y, int iconSize)