Java Code Examples for java.awt.image.DataBufferByte

The following are top voted examples for showing how to use java.awt.image.DataBufferByte. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Face-detection-and-recognition-desktop-application   File: FaceRecognizeFrame.java   Source Code and License 7 votes vote down vote up
private Mat conv_Mat(BufferedImage img) {
    byte[] data = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
    Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
    mat.put(0, 0, data);
    Mat mat1 = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
    Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2HSV);

    return mat1;
}
 
Example 2
Project: Face-detection-and-recognition-desktop-application   File: FaceDetectCropTest.java   Source Code and License 6 votes vote down vote up
private Mat conv_Mat(BufferedImage img) {
    byte[] data = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
    Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
    mat.put(0, 0, data);
    Mat mat1 = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
    Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2HSV);

    return mat1;
}
 
Example 3
Project: GarfieldLanguage   File: Webcam.java   Source Code and License 6 votes vote down vote up
/**
 * Converts/writes a Mat into a BufferedImage.
 *
 * @param matBGR Mat of type CV_8UC3 or CV_8UC1
 * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
 */
public static BufferedImage matrixToBuffer(Mat matBGR) {
   int type = BufferedImage.TYPE_BYTE_GRAY;
   if (matBGR.channels() > 1) {
      type = BufferedImage.TYPE_3BYTE_BGR;
   }
   int width = matBGR.width(), height = matBGR.height(), channels = matBGR.channels();
   byte[] sourcePixels = new byte[width * height * channels];
   matBGR.get(0, 0, sourcePixels);

   // Create new image and get reference to backing data
   image = new BufferedImage(width, height, type);
   final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
   System.arraycopy(sourcePixels, 0, targetPixels, 0, sourcePixels.length);
   return image;
}
 
Example 4
Project: sumo   File: ImageConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the given image to a gl compatible format if necessary and returns the data in the format GL_RGBA as GL_UNSIGNED_BYTE
 * such that the width and height are a power of 2. The image is place in the upper left corner.
 * @param awtImage the image to be converted to an byte buffer
 * @return nio buffer
 */
public static ByteBuffer convertPowerOf2(BufferedImage awtImage)
{
	if(!isGlCompatibleAwtImage(awtImage) || !isPowerOf2(awtImage.getWidth()) || !isPowerOf2(awtImage.getHeight()))
	{
		int width = powerOf2(awtImage.getWidth());
		int height = powerOf2(awtImage.getHeight());
		BufferedImage convertImage = createGlCompatibleAwtImage(width, height);
        // copy the source image into the produced image
        Graphics g = convertImage.getGraphics();
        g.setColor(new Color(0f, 0f, 0f, 0f));
        g.fillRect(0, 0, width, height);
        g.drawImage(awtImage, 0, 0, null);
        awtImage = convertImage;
	}
	
       // build a byte buffer from the temporary image 
       // that be used by OpenGL to produce a texture.
       byte[] data = ((DataBufferByte) awtImage.getRaster().getDataBuffer()).getData(); 
       ByteBuffer imageBuffer = ByteBuffer.allocateDirect(data.length); 
       imageBuffer.order(ByteOrder.nativeOrder()); 
       imageBuffer.put(data, 0, data.length); 
       imageBuffer.flip();
       
       return imageBuffer; 
}
 
Example 5
Project: VASSAL-src   File: MedianCut.java   Source Code and License 6 votes vote down vote up
BufferedImage makeImage() {
// Generate 8-bit image

    //Image img8;
    byte[] pixels8;
    int color16;

    pixels8 = new byte[width*height];
    for (int i=0; i<width*height; i++) {
        color16 = rgb(pixels32[i]);
        pixels8[i] = (byte)hist[color16];
    }

    SampleModel sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, width, new int[] {0});
    DataBufferByte Buffer = new DataBufferByte(pixels8, pixels8.length);
    WritableRaster raster = Raster.createWritableRaster(sampleModel, Buffer, null);

    return new BufferedImage(cm, raster, false, null);
}
 
Example 6
Project: NoMoreOversleeps   File: WebcamDefaultDevice.java   Source Code and License 6 votes vote down vote up
@Override
public BufferedImage getImage()
{

	ByteBuffer buffer = this.getImageBytes();

	if (buffer == null)
	{
		LOG.error("Images bytes buffer is null!");
		return null;
	}

	byte[] bytes = new byte[this.size.width * this.size.height * 3];
	byte[][] data = new byte[][] { bytes };

	buffer.get(bytes);

	DataBufferByte dbuf = new DataBufferByte(data, bytes.length, OFFSET);
	WritableRaster raster = Raster.createWritableRaster(this.smodel, dbuf, null);

	BufferedImage bi = new BufferedImage(this.cmodel, raster, false, null);
	bi.flush();

	return bi;
}
 
Example 7
Project: GUI   File: BitmapLoader.java   Source Code and License 6 votes vote down vote up
private static BufferedImage read24BitBitmap(int nSizeImage, int nHeight, int nWidth, InputStream input) throws IOException {
    int npad = (nSizeImage / nHeight) - nWidth * 3;
    if (npad == 4 || npad < 0)
        npad = 0;
    int nindex = 0;
    BufferedImage bufferedImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_4BYTE_ABGR);
    DataBufferByte dataBufferByte = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer());
    byte[][] bankData = dataBufferByte.getBankData();
    byte brgb[] = new byte[(nWidth + npad) * 3 * nHeight];

    readBuffer(input, brgb);

    for (int j = nHeight - 1; j >= 0; j--) {
        for (int i = 0; i < nWidth; i++) {
            int base = (j * nWidth + i) * 4;
            bankData[0][base] = (byte) 255;
            bankData[0][base + 1] = brgb[nindex];
            bankData[0][base + 2] = brgb[nindex + 1];
            bankData[0][base + 3] = brgb[nindex + 2];
            nindex += 3;
        }
        nindex += npad;
    }

    return bufferedImage;
}
 
Example 8
Project: Rubus   File: Convolution.java   Source Code and License 6 votes vote down vote up
@Before
public void prepare() {
	try {

		File _file = new File(imgFilePath);
		BufferedImage inputImage = ImageIO.read(_file);
		inputImage = resizeImageWithHint(inputImage, inputImage.getType(), size, size);
		height = inputImage.getHeight();
		width = inputImage.getWidth();

		outputImageCPU = new BufferedImage(width, height, inputImage.getType());
		outputImageGPU = new BufferedImage(width, height, inputImage.getType());
		outputImageApar = new BufferedImage(width, height, inputImage.getType());

		imageIn = ((DataBufferByte) inputImage.getRaster().getDataBuffer()).getData();
		imageOutCPU = ((DataBufferByte) outputImageCPU.getRaster().getDataBuffer()).getData();
		imageOutGPU = ((DataBufferByte) outputImageGPU.getRaster().getDataBuffer()).getData();
		imageOutApar = ((DataBufferByte) outputImageApar.getRaster().getDataBuffer()).getData();

	} catch (IOException e) {
		e.printStackTrace();
	}

}
 
Example 9
Project: PengueeBot   File: Frag.java   Source Code and License 6 votes vote down vote up
private int[][] loadFromFile(BufferedImage image) {
	final byte[] pixels = ((DataBufferByte) image.getData().getDataBuffer())
			.getData();
	final int width = image.getWidth();

	if (rgbData == null)
		rgbData = new int[image.getHeight()][width];

	for (int pixel = 0, row = 0; pixel < pixels.length; row++)
		for (int col = 0; col < width; col++, pixel += 3)
			rgbData[row][col] = -16777216 + ((int) pixels[pixel] & 0xFF)
					+ (((int) pixels[pixel + 1] & 0xFF) << 8)
					+ (((int) pixels[pixel + 2] & 0xFF) << 16); // 255
																// alpha, r
																// g b;

	return rgbData;
}
 
Example 10
Project: AquamarineLake   File: CVUtility.java   Source Code and License 6 votes vote down vote up
public static Image matToBufferedImage(Mat m)
{
    // just a simple convertor from web, this code is the fastest one
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if ( m.channels() > 1 ) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    int bufferSize = m.channels()*m.cols()*m.rows();
    byte [] b = new byte[bufferSize];
    m.get(0,0,b);
    BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return image;
    
}
 
Example 11
Project: AquamarineLake   File: CVUtility.java   Source Code and License 6 votes vote down vote up
public static Image matToBufferedImage(Mat m)
{
    // just a simple convertor from web, this code is the fastest one
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if ( m.channels() > 1 ) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    int bufferSize = m.channels()*m.cols()*m.rows();
    byte [] b = new byte[bufferSize];
    m.get(0,0,b);
    BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return image;

}
 
Example 12
Project: OpenJSharp   File: ImageTests.java   Source Code and License 6 votes vote down vote up
public Image makeImage(TestEnvironment env, int w, int h) {
    BufferedImage img = new BufferedImage(w, h, type);
    if (unmanaged) {
        DataBuffer db = img.getRaster().getDataBuffer();
        if (db instanceof DataBufferInt) {
            ((DataBufferInt)db).getData();
        } else if (db instanceof DataBufferShort) {
            ((DataBufferShort)db).getData();
        } else if (db instanceof DataBufferByte) {
            ((DataBufferByte)db).getData();
        } else {
            try {
                img.setAccelerationPriority(0.0f);
            } catch (Throwable e) {}
        }
    }
    return img;
}
 
Example 13
Project: OpenJSharp   File: Buffers.java   Source Code and License 6 votes vote down vote up
/**
  * Create a data buffer of a particular type.
  *
  * @param dataType the desired data type of the buffer.
  * @param size the size of the data buffer bank
  * @param numBanks the number of banks the buffer should have
  */
 public static DataBuffer createBuffer(int dataType, int size, int numBanks)
 {
   switch (dataType)
     {
     case DataBuffer.TYPE_BYTE:
return new DataBufferByte(size, numBanks);
     case DataBuffer.TYPE_SHORT:
return new DataBufferShort(size, numBanks);
     case DataBuffer.TYPE_USHORT:
return new DataBufferUShort(size, numBanks);
     case DataBuffer.TYPE_INT:
return new DataBufferInt(size, numBanks);
     case DataBuffer.TYPE_FLOAT:
return new DataBufferFloat(size, numBanks);
     case DataBuffer.TYPE_DOUBLE:
return new DataBufferDouble(size, numBanks);
     default:
throw new UnsupportedOperationException();
     }
 }
 
Example 14
Project: OpenJSharp   File: Buffers.java   Source Code and License 6 votes vote down vote up
/**
  * Create a data buffer of a particular type.
  *
  * @param dataType the desired data type of the buffer
  * @param data an array containing the data
  * @param size the size of the data buffer bank
  */
 public static DataBuffer createBufferFromData(int dataType, Object data,
					int size)
 {
   switch (dataType)
     {
     case DataBuffer.TYPE_BYTE:
return new DataBufferByte((byte[]) data, size);
     case DataBuffer.TYPE_SHORT:
return new DataBufferShort((short[]) data, size);
     case DataBuffer.TYPE_USHORT:
return new DataBufferUShort((short[]) data, size);
     case DataBuffer.TYPE_INT:
return new DataBufferInt((int[]) data, size);
     case DataBuffer.TYPE_FLOAT:
return new DataBufferFloat((float[]) data, size);
     case DataBuffer.TYPE_DOUBLE:
return new DataBufferDouble((double[]) data, size);
     default:
throw new UnsupportedOperationException();
     }
 }
 
Example 15
Project: FlashLib   File: CvProcessing.java   Source Code and License 6 votes vote down vote up
/**
 * Converts a buffered image object in to an openCV mat.
 * @param image buffered image
 * @return mat
 */
public static Mat bufferedImage2Mat(BufferedImage image){
	byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();  		  
	Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);  		  
	mat.put(0, 0, data);  		  		  
	return mat;  
}
 
Example 16
Project: jdk8u-jdk   File: ImageTests.java   Source Code and License 6 votes vote down vote up
public Image makeImage(TestEnvironment env, int w, int h) {
    BufferedImage img = new BufferedImage(w, h, type);
    if (unmanaged) {
        DataBuffer db = img.getRaster().getDataBuffer();
        if (db instanceof DataBufferInt) {
            ((DataBufferInt)db).getData();
        } else if (db instanceof DataBufferShort) {
            ((DataBufferShort)db).getData();
        } else if (db instanceof DataBufferByte) {
            ((DataBufferByte)db).getData();
        } else {
            try {
                img.setAccelerationPriority(0.0f);
            } catch (Throwable e) {}
        }
    }
    return img;
}
 
Example 17
Project: jdk8u-jdk   File: IncorrectAlphaConversionBicubic.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI(GraphicsConfiguration gc,
                                             int type) {
    BufferedImage img = gc.createCompatibleImage(SIZE, SIZE, type);
    Graphics2D g2d = img.createGraphics();
    g2d.setColor(RGB);
    g2d.fillRect(0, 0, SIZE, SIZE);
    g2d.dispose();
    final DataBuffer db = img.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            img.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return img;
}
 
Example 18
Project: jdk8u-jdk   File: UnmanagedDrawImagePerformance.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI(final int type) {
    final BufferedImage img = new BufferedImage(SIZE, SIZE, type);
    final DataBuffer db = img.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            img.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return img;
}
 
Example 19
Project: jdk8u-jdk   File: IncorrectClipXorModeSW2Surface.java   Source Code and License 6 votes vote down vote up
private static BufferedImage getBufferedImage(int sw) {
    final BufferedImage bi = new BufferedImage(sw, sw, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.setColor(Color.RED);
    g2d.fillRect(0, 0, sw, sw);
    g2d.dispose();

    final DataBuffer db = bi.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            bi.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return bi;
}
 
Example 20
Project: jdk8u-jdk   File: IncorrectUnmanagedImageRotatedClip.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI() {
    final BufferedImage bi = new BufferedImage(500, 200, TYPE_INT_ARGB);
    final DataBuffer db = bi.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            bi.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return bi;
}
 
Example 21
Project: jdk8u-jdk   File: IncorrectUnmanagedImageSourceOffset.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI(final int type) {
    final BufferedImage bi = new BufferedImage(511, 255, type);
    final DataBuffer db = bi.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            bi.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return bi;
}
 
Example 22
Project: openjdk-jdk10   File: ImageTests.java   Source Code and License 6 votes vote down vote up
public Image makeImage(TestEnvironment env, int w, int h) {
    BufferedImage img = new BufferedImage(w, h, type);
    if (unmanaged) {
        DataBuffer db = img.getRaster().getDataBuffer();
        if (db instanceof DataBufferInt) {
            ((DataBufferInt)db).getData();
        } else if (db instanceof DataBufferShort) {
            ((DataBufferShort)db).getData();
        } else if (db instanceof DataBufferByte) {
            ((DataBufferByte)db).getData();
        } else {
            try {
                img.setAccelerationPriority(0.0f);
            } catch (Throwable e) {}
        }
    }
    return img;
}
 
Example 23
Project: openjdk-jdk10   File: IncorrectAlphaConversionBicubic.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI(GraphicsConfiguration gc,
                                             int type) {
    BufferedImage img = gc.createCompatibleImage(SIZE, SIZE, type);
    Graphics2D g2d = img.createGraphics();
    g2d.setColor(RGB);
    g2d.fillRect(0, 0, SIZE, SIZE);
    g2d.dispose();
    final DataBuffer db = img.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            img.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return img;
}
 
Example 24
Project: openjdk-jdk10   File: UnmanagedDrawImagePerformance.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI(final int type) {
    final BufferedImage img = new BufferedImage(SIZE, SIZE, type);
    final DataBuffer db = img.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            img.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return img;
}
 
Example 25
Project: openjdk-jdk10   File: IncorrectClipXorModeSW2Surface.java   Source Code and License 6 votes vote down vote up
private static BufferedImage getBufferedImage(int sw) {
    final BufferedImage bi = new BufferedImage(sw, sw, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.setColor(Color.RED);
    g2d.fillRect(0, 0, sw, sw);
    g2d.dispose();

    final DataBuffer db = bi.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            bi.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return bi;
}
 
Example 26
Project: openjdk-jdk10   File: IncorrectUnmanagedImageRotatedClip.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI() {
    final BufferedImage bi = new BufferedImage(500, 200, TYPE_INT_ARGB);
    final DataBuffer db = bi.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            bi.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return bi;
}
 
Example 27
Project: openjdk-jdk10   File: IncorrectUnmanagedImageSourceOffset.java   Source Code and License 6 votes vote down vote up
private static BufferedImage makeUnmanagedBI(final int type) {
    final BufferedImage bi = new BufferedImage(511, 255, type);
    final DataBuffer db = bi.getRaster().getDataBuffer();
    if (db instanceof DataBufferInt) {
        ((DataBufferInt) db).getData();
    } else if (db instanceof DataBufferShort) {
        ((DataBufferShort) db).getData();
    } else if (db instanceof DataBufferByte) {
        ((DataBufferByte) db).getData();
    } else {
        try {
            bi.setAccelerationPriority(0.0f);
        } catch (final Throwable ignored) {
        }
    }
    return bi;
}
 
Example 28
Project: openjdk-jdk10   File: RasterOpNullDestinationRasterTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {

        byte[][] data = new byte[1][10];
        ByteLookupTable lut = new ByteLookupTable(0, data);
        RasterOp op = new LookupOp(lut, null);

        int[] bandOffsets = {0};
        Point location = new Point(0, 0);
        DataBuffer db = new DataBufferByte(10 * 10);
        SampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
                                                         10, 10, 1, 10,
                                                         bandOffsets);

        Raster src = Raster.createRaster(sm, db, location);

        op.filter(src, null); // this used to result in NullPointerException
    }
 
Example 29
Project: Pixie   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
@Test ()
public void testCopySrcIntoDstAt4()
{
    System.out.println("copySrcIntoDstAt: send image with 1 pixel(RGB), expects 1 pixel(RGB)");

    BufferedImage src = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR);
    src.setRGB(0, 0, 10);

    BufferedImage dst = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR);

    Utils.copySrcIntoDstAt(src, dst);

    DataBufferByte expected = (DataBufferByte) src.getRaster().getDataBuffer();
    DataBufferByte result = (DataBufferByte) dst.getRaster().getDataBuffer();

    assertArrayEquals(expected.getData(), result.getData());
}
 
Example 30
Project: Pixie   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Mirror the image/buffer data
 *
 * @param image the image containing the pixel data which has to be
 * mirrored. This function will alter the bytes of the input image, so that
 * after this function the input image will contain the mirrored information
 */
public static void mirrorImage(BufferedImage image) {
    byte[] bgr = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    byte[] mirror = new byte[bgr.length];
    final int multiplier = 3; // BGR

    for (int j = 0; j < image.getHeight(); j++) {
        for (int i = 0; i < image.getWidth(); i++) {
            mirror[(j * (image.getWidth() * multiplier)) + ((((image.getWidth() - 1) - i) * multiplier) + 0)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 0)]; // R
            mirror[(j * (image.getWidth() * multiplier)) + ((((image.getWidth() - 1) - i) * multiplier) + 1)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 1)]; // G
            mirror[(j * (image.getWidth() * multiplier)) + ((((image.getWidth() - 1) - i) * multiplier) + 2)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 2)]; // B
        }
    }

    System.arraycopy(mirror, 0, bgr, 0, image.getWidth() * image.getHeight() * multiplier);
}
 
Example 31
Project: Pixie   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Flip vertically the image
 *
 * @param image the image containing the pixel data which has to be flipped
 * vertically. This function will alter the bytes of input image, so that
 * after this function the input image will contain the flipped information
 */
public static void flipVerticallyImage(BufferedImage image) {
    byte[] bgr = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    byte[] flipped = new byte[bgr.length];
    final int multiplier = 3; // BGR

    for (int j = 0; j < image.getHeight(); j++) {
        for (int i = 0; i < image.getWidth(); i++) {
            flipped[((image.getHeight() - 1) - j) * (image.getWidth() * multiplier) + (i * multiplier + 0)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 0)]; // R
            flipped[((image.getHeight() - 1) - j) * (image.getWidth() * multiplier) + (i * multiplier + 1)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 1)]; // G
            flipped[((image.getHeight() - 1) - j) * (image.getWidth() * multiplier) + (i * multiplier + 2)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 2)]; // B
        }
    }

    System.arraycopy(flipped, 0, bgr, 0, image.getWidth() * image.getHeight() * multiplier);
}
 
Example 32
Project: BasicsProject   File: GifEncoder.java   Source Code and License 6 votes vote down vote up
/**
 * Extracts image pixels into byte array "pixels"
 */
protected void getImagePixels() {
    int w = image.getWidth();
    int h = image.getHeight();
    int type = image.getType();
    if ((w != width)
            || (h != height)
            || (type != BufferedImage.TYPE_3BYTE_BGR)) {
        // create new image with right size/format
        BufferedImage temp =
                new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = temp.createGraphics();
        g.drawImage(image, 0, 0, null);
        image = temp;
    }
    pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
}
 
Example 33
Project: incubator-netbeans   File: ImageBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public DataBuffer convert(FieldAccessor fa, Instance instance) throws FieldAccessor.InvalidFieldException {
    int size = fa.getInt(instance, "size");                        // NOI18N
    int[] offsets = fa.getIntArray(instance, "offsets", false);      // NOI18N
    byte[][] bankdata = fa.getByteArray2(instance, "bankdata", false); // NOI18N
    return new DataBufferByte(bankdata, size, offsets);
}
 
Example 34
Project: DeepID   File: MainGUI.java   Source Code and License 5 votes vote down vote up
public static Rect[] detectFaces(BufferedImage image)
{
    CascadeClassifier detector = new CascadeClassifier(Thread.currentThread().getContextClassLoader().getResource("haarcascade_frontalface_alt.xml").getFile());
    Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
    byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    mat.put(0, 0, data);
    MatOfRect detections = new MatOfRect();
    detector.detectMultiScale(mat, detections);

    return detections.toArray();
}
 
Example 35
Project: DeepID   File: Identification.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {
    BufferedImage bi = webcam.getImage();

    //Detect all face samples in the preview
        CascadeClassifier detector = new CascadeClassifier(Thread.currentThread().getContextClassLoader().getResource("haarcascade_frontalface_alt.xml").getFile());
        Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
        byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
        mat.put(0, 0, data);
        MatOfRect detections = new MatOfRect();
        detector.detectMultiScale(mat, detections);

        Rect[] array = detections.toArray();

        if (array.length == 1) { //If there's only one face detected, resize the sample to 150x150 pixels and send it to the model
            BufferedImage bi2 = new BufferedImage(150, 150, BufferedImage.TYPE_INT_RGB);
            Graphics gr = bi2.createGraphics();
            gr.drawImage(bi.getSubimage(array[0].x, array[0].y, array[0].width, array[0].height), 0, 0, 150, 150, null);
            gr.dispose();

            try {
                check(bi2); //sends the image to the model
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
}
 
Example 36
Project: GlitchKernel   File: DataAsSound.java   Source Code and License 5 votes vote down vote up
@Override
public byte[] glitchPixels(byte[] inputImageBytes) throws Exception 
{
	int audioBitRate = ((Integer) getPixelGlitchParameters().get("bitRateBlend")).intValue();
	float bitRateBlend = (float) audioBitRate / 10;
	if(bitRateBlend < 0.1F || bitRateBlend > 0.9F)
	{
		return null;
	}
	
	BufferedImage inputImage = ImageUtil.getImageFromBytes(inputImageBytes);
	InputStream imageInputStream = new ByteArrayInputStream(inputImageBytes);
	AudioInputStream distortionAudioStream = new AudioInputStream(imageInputStream, new AudioFormat(AudioFormat.Encoding.ULAW, ThreadLocalRandom.current().nextInt(8000,  20000), 8, 5, 9, ThreadLocalRandom.current().nextInt(8000,  20000), true), inputImageBytes.length);
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	AudioSystem.write(distortionAudioStream, Type.WAVE, outputStream);
	BufferedImage outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	byte[] imageData = ((DataBufferByte) outputImage.getRaster().getDataBuffer()).getData();
	System.arraycopy(outputStream.toByteArray(),0,imageData,0,outputStream.toByteArray().length);
	int[] abgrOffsets = {3, 2, 1, 0}; 
	DataBuffer outputBuffer = new DataBufferByte(imageData, imageData.length);
    WritableRaster raster = Raster.createInterleavedRaster(outputBuffer, inputImage.getWidth(), inputImage.getHeight(), 4 * inputImage.getWidth(), 4, abgrOffsets, null);
    ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    BufferedImage rasterizedImage = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
    rasterizedImage = resizeImage(rasterizedImage, inputImage.getWidth() * 4, inputImage.getHeight() * 4);
    Graphics2D g2d = rasterizedImage.createGraphics();
    g2d.setComposite(AlphaComposite.SrcOver.derive(bitRateBlend));
    g2d.drawImage(inputImage, 0, 0, null);
    g2d.dispose();
    rasterizedImage = rasterizedImage.getSubimage(0, 0, inputImage.getWidth(), inputImage.getHeight());
	return ImageUtil.getImageBytes(rasterizedImage);
}
 
Example 37
Project: GlitchKernel   File: DataBend.java   Source Code and License 5 votes vote down vote up
private static BufferedImage createRGBImage(byte[] bytes, int width, int height) 
{
    DataBufferByte buffer = new DataBufferByte(bytes, bytes.length);
    ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[]{8, 8, 8}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm, Raster.createInterleavedRaster(buffer, width, height, width * 3, 3, new int[]{0, 1, 2}, null), false, null);
}
 
Example 38
Project: sumo   File: ImageConverter.java   Source Code and License 5 votes vote down vote up
public static boolean isGlCompatibleAwtImage(BufferedImage img)
{
	if(img.getColorModel() != COLOR_MODEL) return false;
	if(!(img.getRaster().getDataBuffer() instanceof DataBufferByte)) return false;
	if(img.getRaster().getDataBuffer().getNumBanks() != 4) return false;
	return true;
}
 
Example 39
Project: sumo   File: ImageConverter.java   Source Code and License 5 votes vote down vote up
/**
 * Converts the given image to a gl compatible format if necessary and returns the data in the format GL_RGBA as GL_UNSIGNED_BYTE.
 * @param awtImage the image to be converted to an byte buffer
 * @return nio buffer
 */
public static ByteBuffer convert(BufferedImage awtImage)
{
	if(!isGlCompatibleAwtImage(awtImage))
	{
		BufferedImage convertImage = createGlCompatibleAwtImage(awtImage.getWidth(), awtImage.getHeight());
        // copy the source image into the produced image
        Graphics g = convertImage.getGraphics();
        g.setColor(new Color(0f, 0f, 0f, 0f));
        g.fillRect(0, 0, awtImage.getWidth(), awtImage.getHeight());
        g.drawImage(awtImage, 0, 0, null);
        awtImage = convertImage;
	}
	
       // build a byte buffer from the temporary image 
       // that be used by OpenGL to produce a texture.
       byte[] data = ((DataBufferByte) awtImage.getRaster().getDataBuffer()).getData(); 
       ByteBuffer imageBuffer = ByteBuffer.allocateDirect(data.length); 
       imageBuffer.order(ByteOrder.nativeOrder()); 
       imageBuffer.put(data, 0, data.length); 
       imageBuffer.flip();
       
       return imageBuffer; 
}
 
Example 40
Project: Face-Detection-and-Tracking   File: FaceTrackMain.java   Source Code and License 5 votes vote down vote up
public static BufferedImage Mat2BufferedImage(Mat m) {
	//Method converts a Mat to a Buffered Image
	int type = BufferedImage.TYPE_BYTE_GRAY;
     if ( m.channels() > 1 ) {
         type = BufferedImage.TYPE_3BYTE_BGR;
     }
     int bufferSize = m.channels()*m.cols()*m.rows();
     byte [] b = new byte[bufferSize];
     m.get(0,0,b); // get all the pixels
     BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
     final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
     System.arraycopy(b, 0, targetPixels, 0, b.length);  
     return image;
}
 
Example 41
Project: omr-dataset-tools   File: SubImages.java   Source Code and License 5 votes vote down vote up
/**
 * Build the sub-image that corresponds to the provided row of features.
 *
 * @param row the flat row of pixel values
 * @return the bufferedImage
 */
public static BufferedImage buildSubImage (INDArray row)
{
    // Build a gray image with vector values
    BufferedImage grayImg = new BufferedImage(
            CONTEXT_WIDTH,
            CONTEXT_HEIGHT,
            BufferedImage.TYPE_BYTE_GRAY);
    WritableRaster raster = grayImg.getRaster();
    DataBuffer buffer = raster.getDataBuffer();
    DataBufferByte byteBuffer = (DataBufferByte) buffer;

    for (int r = 0; r < CONTEXT_HEIGHT; r++) {
        int offset = r * CONTEXT_WIDTH;

        for (int c = 0; c < CONTEXT_WIDTH; c++) {
            int i = offset + c;
            int val = (int) Math.rint(row.getDouble(i));
            val = 255 - val; // Inversion
            byteBuffer.setElem(i, val);
        }
    }

    // Draw colored reference lines on top of image
    BufferedImage colorImg = new BufferedImage(
            CONTEXT_WIDTH,
            CONTEXT_HEIGHT,
            BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D g = colorImg.createGraphics();
    g.drawImage(grayImg, null, null);
    g.setColor(CROSS_COLOR);
    g.drawLine(CONTEXT_WIDTH / 2, 0, CONTEXT_WIDTH / 2, CONTEXT_HEIGHT);
    g.drawLine(0, CONTEXT_HEIGHT / 2, CONTEXT_WIDTH, CONTEXT_HEIGHT / 2);
    g.dispose();

    return colorImg;
}
 
Example 42
Project: OptimizedImageEnhance   File: ImShow.java   Source Code and License 5 votes vote down vote up
public BufferedImage toBufferedImage(Mat m) {
	int type = BufferedImage.TYPE_BYTE_GRAY;
	if (m.channels() > 1) type = BufferedImage.TYPE_3BYTE_BGR;
	int bufferSize = m.channels() * m.cols() * m.rows();
	byte[] b = new byte[bufferSize];
	m.get(0, 0, b); // get all the pixels
	BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
	final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
	System.arraycopy(b, 0, targetPixels, 0, b.length);
	return image;
}
 
Example 43
Project: rcom   File: VideoStreamProcessor.java   Source Code and License 5 votes vote down vote up
protected void readFrames(InputStream inputStream) {
	try {
		long t0=System.currentTimeMillis()-1; // -1: Avoid div by zero in very fast cases
		while(true)
		{
			BufferedImage im=frames[writePtr];
			DataBufferByte b=(DataBufferByte)im.getRaster().getDataBuffer();
			byte[] data=b.getData();
			int at=0;
			while(at<data.length)
			{
				int n=inputStream.read(data, at, data.length-at);
				if(n<0)
				{
					throw new EOFException();
				}
				at+=n;
			}
			nRead++;
			writePtr++;
			writePtr%=frames.length;
			long t=System.currentTimeMillis();
			fps=((double)nRead)/(t-t0)*1000;
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 44
Project: kronometer   File: Utility.java   Source Code and License 5 votes vote down vote up
public Mat bufferedImageToMat(BufferedImage bi) {
    Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
    byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
    mat.put(0, 0, data);
    return mat;
}
 
Example 45
Project: AquamarineLake   File: DrawPanel.java   Source Code and License 5 votes vote down vote up
public BufferedImage matToBufferedImage(Mat mat) {

        if (mat.height() > 0 && mat.width() > 0) {
            BufferedImage image = new BufferedImage(mat.width(), mat.height(), BufferedImage.TYPE_3BYTE_BGR);
            WritableRaster raster = image.getRaster();
            DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
            byte[] data = dataBuffer.getData();
            mat.get(0, 0, data);
            return image;
        }
        return null;
    }
 
Example 46
Project: AquamarineLake   File: DrawPanel.java   Source Code and License 5 votes vote down vote up
public Image enhancedMatToBufferedImage(Mat m){
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if ( m.channels() > 1 ) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    int bufferSize = m.channels()*m.cols()*m.rows();
    byte [] b = new byte[bufferSize];
    m.get(0,0,b); // get all the pixels
    BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return image;

}
 
Example 47
Project: AquamarineLake   File: DrawPanel.java   Source Code and License 5 votes vote down vote up
public BufferedImage bufferedImage(Mat mat) {

        if (mat.height() > 0 && mat.width() > 0) {
            BufferedImage image = new BufferedImage(mat.width(), mat.height(), BufferedImage.TYPE_3BYTE_BGR);
            WritableRaster raster = image.getRaster();
            DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
            byte[] data = dataBuffer.getData();
            mat.get(0, 0, data);
            return image;
        }
        return null;
    }
 
Example 48
Project: OpenJSharp   File: ByteBandedRaster.java   Source Code and License 5 votes vote down vote up
/**
 *  Constructs a ByteBandedRaster with the given sampleModel,
 *  DataBuffer, and parent. DataBuffer must be a DataBufferShort and
 *  SampleModel must be of type BandedSampleModel.
 *  When translated into the base Raster's
 *  coordinate system, aRegion must be contained by the base Raster.
 *  Origin is the coordinate in the new Raster's coordinate system of
 *  the origin of the base Raster.  (The base Raster is the Raster's
 *  ancestor which has no parent.)
 *
 *  Note that this constructor should generally be called by other
 *  constructors or create methods, it should not be used directly.
 *  @param sampleModel     The SampleModel that specifies the layout.
 *  @param dataBuffer      The DataBufferShort that contains the image data.
 *  @param aRegion         The Rectangle that specifies the image area.
 *  @param origin          The Point that specifies the origin.
 *  @param parent          The parent (if any) of this raster.
 */
public ByteBandedRaster(SampleModel sampleModel,
                        DataBuffer dataBuffer,
                        Rectangle aRegion,
                        Point origin,
                        ByteBandedRaster parent) {

    super(sampleModel, dataBuffer, aRegion, origin, parent);
    this.maxX = minX + width;
    this.maxY = minY + height;

    if (!(dataBuffer instanceof DataBufferByte)) {
       throw new RasterFormatException("ByteBandedRaster must have" +
            "byte DataBuffers");
    }
    DataBufferByte dbb = (DataBufferByte)dataBuffer;

    if (sampleModel instanceof BandedSampleModel) {
        BandedSampleModel bsm = (BandedSampleModel)sampleModel;
        this.scanlineStride = bsm.getScanlineStride();
        int bankIndices[] = bsm.getBankIndices();
        int bandOffsets[] = bsm.getBandOffsets();
        int dOffsets[] = dbb.getOffsets();
        dataOffsets = new int[bankIndices.length];
        data = new byte[bankIndices.length][];
        int xOffset = aRegion.x - origin.x;
        int yOffset = aRegion.y - origin.y;
        for (int i = 0; i < bankIndices.length; i++) {
           data[i] = stealData(dbb, bankIndices[i]);
           dataOffsets[i] = dOffsets[bankIndices[i]] +
               xOffset + yOffset*scanlineStride + bandOffsets[i];
        }
    } else {
        throw new RasterFormatException("ByteBandedRasters must have"+
            "BandedSampleModels");
    }
    verify();
}
 
Example 49
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
BufferedImage getThumbnail(ImageInputStream iis,
                           JPEGImageReader reader)
    throws IOException {
    iis.mark();
    iis.seek(streamPos);
    DataBufferByte buffer = new DataBufferByte(getLength());
    readByteBuffer(iis,
                   buffer.getData(),
                   reader,
                   1.0F,
                   0.0F);
    iis.reset();

    WritableRaster raster =
        Raster.createInterleavedRaster(buffer,
                                       thumbWidth,
                                       thumbHeight,
                                       thumbWidth*3,
                                       3,
                                       new int [] {0, 1, 2},
                                       null);
    ColorModel cm = new ComponentColorModel(JPEG.JCS.sRGB,
                                            false,
                                            false,
                                            ColorModel.OPAQUE,
                                            DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm,
                             raster,
                             false,
                             null);
}
 
Example 50
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
BufferedImage getThumbnail(ImageInputStream iis,
                           JPEGImageReader reader)
    throws IOException {
    iis.mark();
    iis.seek(streamPos);
    // read the palette
    byte [] palette = new byte [PALETTE_SIZE];
    float palettePart = ((float) PALETTE_SIZE) / getLength();
    readByteBuffer(iis,
                   palette,
                   reader,
                   palettePart,
                   0.0F);
    DataBufferByte buffer = new DataBufferByte(thumbWidth*thumbHeight);
    readByteBuffer(iis,
                   buffer.getData(),
                   reader,
                   1.0F-palettePart,
                   palettePart);
    iis.read();
    iis.reset();

    IndexColorModel cm = new IndexColorModel(8,
                                             256,
                                             palette,
                                             0,
                                             false);
    SampleModel sm = cm.createCompatibleSampleModel(thumbWidth,
                                                    thumbHeight);
    WritableRaster raster =
        Raster.createWritableRaster(sm, buffer, null);
    return new BufferedImage(cm,
                             raster,
                             false,
                             null);
}
 
Example 51
Project: ImageEnhanceViaFusion   File: ImShow.java   Source Code and License 5 votes vote down vote up
public BufferedImage toBufferedImage(Mat m) {
	int type = BufferedImage.TYPE_BYTE_GRAY;
	if (m.channels() > 1) {
		type = BufferedImage.TYPE_3BYTE_BGR;
	}
	int bufferSize = m.channels() * m.cols() * m.rows();
	byte[] b = new byte[bufferSize];
	m.get(0, 0, b); // get all the pixels
	BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
	final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
	System.arraycopy(b, 0, targetPixels, 0, b.length);
	return image;

}
 
Example 52
Project: JuggleMasterPro   File: AnimatedGIFEncoder.java   Source Code and License 5 votes vote down vote up
/**
 * Extracts image pixels into byte array "pixels"
 */
protected void getImagePixels() {
	if ((this.imgGbuffer.getWidth() != this.intGwidth) || (this.imgGbuffer.getHeight() != this.intGheight)
		|| (this.imgGbuffer.getType() != BufferedImage.TYPE_3BYTE_BGR)) {
		// create new image with right size/format
		final BufferedImage imgLbuffer = new BufferedImage(this.intGwidth, this.intGheight, BufferedImage.TYPE_3BYTE_BGR);
		final Graphics2D g = imgLbuffer.createGraphics();
		g.drawImage(this.imgGbuffer, 0, 0, null);
		this.imgGbuffer = imgLbuffer;
	}
	this.bytGpixelA = ((DataBufferByte) this.imgGbuffer.getRaster().getDataBuffer()).getData();
}
 
Example 53
Project: jdk8u-jdk   File: ByteBandedRaster.java   Source Code and License 5 votes vote down vote up
/**
 *  Constructs a ByteBandedRaster with the given sampleModel,
 *  DataBuffer, and parent. DataBuffer must be a DataBufferShort and
 *  SampleModel must be of type BandedSampleModel.
 *  When translated into the base Raster's
 *  coordinate system, aRegion must be contained by the base Raster.
 *  Origin is the coordinate in the new Raster's coordinate system of
 *  the origin of the base Raster.  (The base Raster is the Raster's
 *  ancestor which has no parent.)
 *
 *  Note that this constructor should generally be called by other
 *  constructors or create methods, it should not be used directly.
 *  @param sampleModel     The SampleModel that specifies the layout.
 *  @param dataBuffer      The DataBufferShort that contains the image data.
 *  @param aRegion         The Rectangle that specifies the image area.
 *  @param origin          The Point that specifies the origin.
 *  @param parent          The parent (if any) of this raster.
 */
public ByteBandedRaster(SampleModel sampleModel,
                        DataBuffer dataBuffer,
                        Rectangle aRegion,
                        Point origin,
                        ByteBandedRaster parent) {

    super(sampleModel, dataBuffer, aRegion, origin, parent);
    this.maxX = minX + width;
    this.maxY = minY + height;

    if (!(dataBuffer instanceof DataBufferByte)) {
       throw new RasterFormatException("ByteBandedRaster must have" +
            "byte DataBuffers");
    }
    DataBufferByte dbb = (DataBufferByte)dataBuffer;

    if (sampleModel instanceof BandedSampleModel) {
        BandedSampleModel bsm = (BandedSampleModel)sampleModel;
        this.scanlineStride = bsm.getScanlineStride();
        int bankIndices[] = bsm.getBankIndices();
        int bandOffsets[] = bsm.getBandOffsets();
        int dOffsets[] = dbb.getOffsets();
        dataOffsets = new int[bankIndices.length];
        data = new byte[bankIndices.length][];
        int xOffset = aRegion.x - origin.x;
        int yOffset = aRegion.y - origin.y;
        for (int i = 0; i < bankIndices.length; i++) {
           data[i] = stealData(dbb, bankIndices[i]);
           dataOffsets[i] = dOffsets[bankIndices[i]] +
               xOffset + yOffset*scanlineStride + bandOffsets[i];
        }
    } else {
        throw new RasterFormatException("ByteBandedRasters must have"+
            "BandedSampleModels");
    }
    verify();
}
 
Example 54
Project: jdk8u-jdk   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
BufferedImage getThumbnail(ImageInputStream iis,
                           JPEGImageReader reader)
    throws IOException {
    iis.mark();
    iis.seek(streamPos);
    DataBufferByte buffer = new DataBufferByte(getLength());
    readByteBuffer(iis,
                   buffer.getData(),
                   reader,
                   1.0F,
                   0.0F);
    iis.reset();

    WritableRaster raster =
        Raster.createInterleavedRaster(buffer,
                                       thumbWidth,
                                       thumbHeight,
                                       thumbWidth*3,
                                       3,
                                       new int [] {0, 1, 2},
                                       null);
    ColorModel cm = new ComponentColorModel(JPEG.JCS.sRGB,
                                            false,
                                            false,
                                            ColorModel.OPAQUE,
                                            DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm,
                             raster,
                             false,
                             null);
}
 
Example 55
Project: jdk8u-jdk   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
BufferedImage getThumbnail(ImageInputStream iis,
                           JPEGImageReader reader)
    throws IOException {
    iis.mark();
    iis.seek(streamPos);
    // read the palette
    byte [] palette = new byte [PALETTE_SIZE];
    float palettePart = ((float) PALETTE_SIZE) / getLength();
    readByteBuffer(iis,
                   palette,
                   reader,
                   palettePart,
                   0.0F);
    DataBufferByte buffer = new DataBufferByte(thumbWidth*thumbHeight);
    readByteBuffer(iis,
                   buffer.getData(),
                   reader,
                   1.0F-palettePart,
                   palettePart);
    iis.read();
    iis.reset();

    IndexColorModel cm = new IndexColorModel(8,
                                             256,
                                             palette,
                                             0,
                                             false);
    SampleModel sm = cm.createCompatibleSampleModel(thumbWidth,
                                                    thumbHeight);
    WritableRaster raster =
        Raster.createWritableRaster(sm, buffer, null);
    return new BufferedImage(cm,
                             raster,
                             false,
                             null);
}
 
Example 56
Project: openjdk-jdk10   File: ByteComponentRaster.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a ByteComponentRaster with the given SampleModel.
 * The Raster's upper left corner is origin and it is the same
 * size as the SampleModel.  A DataBuffer large enough to describe the
 * Raster is automatically created.  SampleModel must be of type
 * SinglePixelPackedSampleModel or ComponentSampleModel.
 * @param sampleModel     The SampleModel that specifies the layout.
 * @param origin          The Point that specified the origin.
 */
public ByteComponentRaster(SampleModel sampleModel, Point origin) {
    this(sampleModel,
         (DataBufferByte) sampleModel.createDataBuffer(),
         new Rectangle(origin.x,
                       origin.y,
                       sampleModel.getWidth(),
                       sampleModel.getHeight()),
         origin,
         null);
}
 
Example 57
Project: openjdk-jdk10   File: ByteComponentRaster.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a ByteComponentRaster with the given SampleModel
 * and DataBuffer.  The Raster's upper left corner is origin and
 * it is the same size as the SampleModel.  The DataBuffer is not
 * initialized and must be a DataBufferByte compatible with SampleModel.
 * SampleModel must be of type SinglePixelPackedSampleModel
 * or ComponentSampleModel.
 * @param sampleModel     The SampleModel that specifies the layout.
 * @param dataBuffer      The DataBufferByte that contains the image data.
 * @param origin          The Point that specifies the origin.
 */
public ByteComponentRaster(SampleModel sampleModel,
                           DataBufferByte dataBuffer,
                           Point origin)
{
    this(sampleModel,
         dataBuffer,
         new Rectangle(origin.x,
                       origin.y,
                       sampleModel.getWidth(),
                       sampleModel.getHeight()),
         origin,
         null);
}
 
Example 58
Project: openjdk-jdk10   File: ByteComponentRaster.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a Writable subRaster given a region of the Raster. The x and y
 * coordinates specify the horizontal and vertical offsets
 * from the upper-left corner of this Raster to the upper-left corner
 * of the subRaster.  A subset of the bands of the parent Raster may
 * be specified.  If this is null, then all the bands are present in the
 * subRaster. A translation to the subRaster may also be specified.
 * Note that the subRaster will reference the same
 * DataBuffer as the parent Raster, but using different offsets.
 * @param x               X offset.
 * @param y               Y offset.
 * @param width           Width (in pixels) of the subraster.
 * @param height          Height (in pixels) of the subraster.
 * @param x0              Translated X origin of the subraster.
 * @param y0              Translated Y origin of the subraster.
 * @param bandList        Array of band indices.
 * @exception RasterFormatException
 *            if the specified bounding box is outside of the parent Raster.
 */
public WritableRaster createWritableChild(int x, int y,
                                          int width, int height,
                                          int x0, int y0,
                                          int[] bandList) {
    if (x < this.minX) {
        throw new RasterFormatException("x lies outside the raster");
    }
    if (y < this.minY) {
        throw new RasterFormatException("y lies outside the raster");
    }
    if ((x+width < x) || (x+width > this.minX + this.width)) {
        throw new RasterFormatException("(x + width) is outside of Raster");
    }
    if ((y+height < y) || (y+height > this.minY + this.height)) {
        throw new RasterFormatException("(y + height) is outside of Raster");
    }

    SampleModel sm;

    if (bandList != null)
        sm = sampleModel.createSubsetSampleModel(bandList);
    else
        sm = sampleModel;

    int deltaX = x0 - x;
    int deltaY = y0 - y;

    return new ByteComponentRaster(sm,
                                   (DataBufferByte) dataBuffer,
                                   new Rectangle(x0, y0, width, height),
                                   new Point(sampleModelTranslateX+deltaX,
                                             sampleModelTranslateY+deltaY),
                                   this);
}
 
Example 59
Project: openjdk-jdk10   File: ByteBandedRaster.java   Source Code and License 5 votes vote down vote up
/**
 *  Constructs a ByteBandedRaster with the given sampleModel. The
 *  Raster's upper left corner is origin and it is the same
 *  size as the SampleModel.  A dataBuffer large
 *  enough to describe the Raster is automatically created. SampleModel
 *  must be of type BandedSampleModel.
 *  @param sampleModel     The SampleModel that specifies the layout.
 *  @param origin          The Point that specifies the origin.
 */
public ByteBandedRaster(SampleModel sampleModel, Point origin) {
    this(sampleModel,
         (DataBufferByte) sampleModel.createDataBuffer(),
         new Rectangle(origin.x,
                       origin.y,
                       sampleModel.getWidth(),
                       sampleModel.getHeight()),
         origin,
         null);
}
 
Example 60
Project: openjdk-jdk10   File: ByteBandedRaster.java   Source Code and License 5 votes vote down vote up
/**
 *  Constructs a ByteBanded Raster with the given sampleModel
 *  and DataBuffer. The Raster's upper left corner is origin and
 *  it is the same size as the SampleModel.  The DataBuffer is not
 *  initialized and must be a DataBufferShort compatible with SampleModel.
 *  SampleModel must be of type BandedSampleModel.
 *  @param sampleModel     The SampleModel that specifies the layout.
 *  @param dataBuffer      The DataBufferByte that contains the image data.
 *  @param origin          The Point that specifies the origin.
 */
public ByteBandedRaster(SampleModel sampleModel,
                        DataBufferByte dataBuffer,
                        Point origin)
{
    this(sampleModel, dataBuffer,
         new Rectangle(origin.x , origin.y,
                       sampleModel.getWidth(),
                       sampleModel.getHeight()),
         origin, null);
}