下面列出了java.awt.image.DataBuffer#TYPE_BYTE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Converts the source image to 4-bit colour
* using the given colour map. No transparency.
* @param src the source image to convert
* @param cmap the colour map, which should contain no more than 16 entries
* The entries are in the form RRGGBB (hex).
* @return a copy of the source image with a 4-bit colour depth, with the custom colour pallette
*/
public static BufferedImage convert4(BufferedImage src, int[] cmap) {
IndexColorModel icm = new IndexColorModel(
4, cmap.length, cmap, 0, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE
);
BufferedImage dest = new BufferedImage(
src.getWidth(), src.getHeight(),
BufferedImage.TYPE_BYTE_BINARY,
icm
);
ColorConvertOp cco = new ColorConvertOp(
src.getColorModel().getColorSpace(),
dest.getColorModel().getColorSpace(),
null
);
cco.filter(src, dest);
return dest;
}
/**
* Gets the raster's pixel data as arrays of primitives, one per channel. The
* returned type will be either byte[][], short[][], int[][], float[][] or
* double[][], depending on the raster's transfer type.
*/
public static Object getPixels(final WritableRaster raster, final int x,
final int y, final int w, final int h)
{
final int tt = raster.getTransferType();
if (tt == DataBuffer.TYPE_BYTE) return getBytes(raster, x, y, w, h);
else if (tt == DataBuffer.TYPE_USHORT || tt == DataBuffer.TYPE_SHORT) {
return getShorts(raster, x, y, w, h);
}
else if (tt == DataBuffer.TYPE_INT) return getInts(raster, x, y, w, h);
else if (tt == DataBuffer.TYPE_FLOAT) return getFloats(raster, x, y, w, h);
else if (tt == DataBuffer.TYPE_DOUBLE) {
return getDoubles(raster, x, y, w, h);
}
else return null;
}
static String getDTName(int dType) {
switch(dType) {
case DataBuffer.TYPE_BYTE:
return "TYPE_BYTE";
case DataBuffer.TYPE_DOUBLE:
return "TYPE_DOUBLE";
case DataBuffer.TYPE_FLOAT:
return "TYPE_FLOAT";
case DataBuffer.TYPE_INT:
return "TYPE_INT";
case DataBuffer.TYPE_SHORT:
return "TYPE_SHORT";
case DataBuffer.TYPE_USHORT:
return "TYPE_USHORT";
case DataBuffer.TYPE_UNDEFINED:
return "TYPE_UNDEFINED";
}
return "UNKNOWN";
}
static PixelWriter createXorPixelWriter(SunGraphics2D sg2d,
SurfaceData sData)
{
ColorModel dstCM = sData.getColorModel();
Object srcPixel = dstCM.getDataElements(sg2d.eargb, null);
XORComposite comp = (XORComposite)sg2d.getComposite();
int xorrgb = comp.getXorColor().getRGB();
Object xorPixel = dstCM.getDataElements(xorrgb, null);
switch (dstCM.getTransferType()) {
case DataBuffer.TYPE_BYTE:
return new XorPixelWriter.ByteData(srcPixel, xorPixel);
case DataBuffer.TYPE_SHORT:
case DataBuffer.TYPE_USHORT:
return new XorPixelWriter.ShortData(srcPixel, xorPixel);
case DataBuffer.TYPE_INT:
return new XorPixelWriter.IntData(srcPixel, xorPixel);
case DataBuffer.TYPE_FLOAT:
return new XorPixelWriter.FloatData(srcPixel, xorPixel);
case DataBuffer.TYPE_DOUBLE:
return new XorPixelWriter.DoubleData(srcPixel, xorPixel);
default:
throw new InternalError("Unsupported XOR pixel type");
}
}
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);
}
static PixelWriter createXorPixelWriter(SunGraphics2D sg2d,
SurfaceData sData)
{
ColorModel dstCM = sData.getColorModel();
Object srcPixel = dstCM.getDataElements(sg2d.eargb, null);
XORComposite comp = (XORComposite)sg2d.getComposite();
int xorrgb = comp.getXorColor().getRGB();
Object xorPixel = dstCM.getDataElements(xorrgb, null);
switch (dstCM.getTransferType()) {
case DataBuffer.TYPE_BYTE:
return new XorPixelWriter.ByteData(srcPixel, xorPixel);
case DataBuffer.TYPE_SHORT:
case DataBuffer.TYPE_USHORT:
return new XorPixelWriter.ShortData(srcPixel, xorPixel);
case DataBuffer.TYPE_INT:
return new XorPixelWriter.IntData(srcPixel, xorPixel);
case DataBuffer.TYPE_FLOAT:
return new XorPixelWriter.FloatData(srcPixel, xorPixel);
case DataBuffer.TYPE_DOUBLE:
return new XorPixelWriter.DoubleData(srcPixel, xorPixel);
default:
throw new InternalError("Unsupported XOR pixel type");
}
}
public int rgbToPixel(int rgb, ColorModel cm) {
Object obj = cm.getDataElements(rgb, null);
switch (cm.getTransferType()) {
case DataBuffer.TYPE_BYTE:
byte[] bytearr = (byte[]) obj;
int pix = 0;
switch(bytearr.length) {
default: // bytearr.length >= 4
pix = bytearr[3] << 24;
// FALLSTHROUGH
case 3:
pix |= (bytearr[2] & 0xff) << 16;
// FALLSTHROUGH
case 2:
pix |= (bytearr[1] & 0xff) << 8;
// FALLSTHROUGH
case 1:
pix |= (bytearr[0] & 0xff);
}
return pix;
case DataBuffer.TYPE_SHORT:
case DataBuffer.TYPE_USHORT:
short[] shortarr = (short[]) obj;
return (((shortarr.length > 1) ? shortarr[1] << 16 : 0) |
shortarr[0] & 0xffff);
case DataBuffer.TYPE_INT:
return ((int[]) obj)[0];
default:
return rgb;
}
}
public int rgbToPixel(int rgb, ColorModel cm) {
Object obj = cm.getDataElements(rgb, null);
switch (cm.getTransferType()) {
case DataBuffer.TYPE_BYTE:
byte[] bytearr = (byte[]) obj;
int pix = 0;
switch(bytearr.length) {
default: // bytearr.length >= 4
pix = bytearr[3] << 24;
// FALLSTHROUGH
case 3:
pix |= (bytearr[2] & 0xff) << 16;
// FALLSTHROUGH
case 2:
pix |= (bytearr[1] & 0xff) << 8;
// FALLSTHROUGH
case 1:
pix |= (bytearr[0] & 0xff);
}
return pix;
case DataBuffer.TYPE_SHORT:
case DataBuffer.TYPE_USHORT:
short[] shortarr = (short[]) obj;
return (((shortarr.length > 1) ? shortarr[1] << 16 : 0) |
shortarr[0] & 0xffff);
case DataBuffer.TYPE_INT:
return ((int[]) obj)[0];
default:
return rgb;
}
}
/**
* Create a Java color model for this colorspace.
*
* @param bpc The number of bits per component.
*
* @return A color model that can be used for Java AWT operations.
*
* @throws IOException If there is an error creating the color model.
*/
public ColorModel createColorModel( int bpc ) throws IOException
{
int[] nbBits;
int numOfComponents = getNumberOfComponents();
switch (numOfComponents)
{
case 1:
// DeviceGray
nbBits = new int[]{ bpc };
break;
case 3:
// DeviceRGB
nbBits = new int[]{ bpc, bpc, bpc };
break;
case 4:
// DeviceCMYK
nbBits = new int[]{ bpc, bpc, bpc, bpc };
break;
default:
throw new IOException( "Unknown colorspace number of components:" + numOfComponents );
}
ComponentColorModel componentColorModel =
new ComponentColorModel( getJavaColorSpace(),
nbBits,
false,
false,
Transparency.OPAQUE,
DataBuffer.TYPE_BYTE );
return componentColorModel;
}
protected IndexColorModel createTestICM(int numColors) {
int[] palette = createTestPalette(numColors);
int numBits = getNumBits(numColors);
IndexColorModel icm = new IndexColorModel(numBits, numColors,
palette, 0, false, -1,
DataBuffer.TYPE_BYTE);
return icm;
}
public static void main(String[] args) {
int[] dataTypes = new int[] {
DataBuffer.TYPE_BYTE,
DataBuffer.TYPE_USHORT,
DataBuffer.TYPE_INT };
for (int type : dataTypes) {
doTest(type);
}
}
public static void main(String args[]) {
BufferedImage src
= new BufferedImage(1, 10, BufferedImage.TYPE_INT_ARGB);
// Set src pixel values
Color pelColor = new Color(100, 100, 100, 128);
for (int i = 0; i < 10; i++) {
src.setRGB(0, i, pelColor.getRGB());
}
ColorModel cm = new ComponentColorModel
(ColorSpace.getInstance(ColorSpace.CS_GRAY),
new int [] {8,8}, true,
src.getColorModel().isAlphaPremultiplied(),
Transparency.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
SampleModel sm = new PixelInterleavedSampleModel
(DataBuffer.TYPE_BYTE, 100, 100, 2, 200,
new int [] { 0, 1 });
WritableRaster wr = Raster.createWritableRaster(sm, new Point(0,0));
BufferedImage dst =
new BufferedImage(cm, wr, cm.isAlphaPremultiplied(), null);
dst = dst.getSubimage(0, 0, 1, 10);
ColorConvertOp op = new ColorConvertOp(null);
op.filter(src, dst);
for (int i = 0; i < 10; i++) {
if (((dst.getRGB(0, i) >> 24) & 0xff) != 128) {
throw new RuntimeException(
"Incorrect destination alpha value.");
}
}
}
public Banded(ColorSpace colorSpace,
int[] bankIndices,
int[] bandOffsets,
int dataType,
boolean hasAlpha,
boolean isAlphaPremultiplied) {
if (colorSpace == null) {
throw new IllegalArgumentException("colorSpace == null!");
}
if (bankIndices == null) {
throw new IllegalArgumentException("bankIndices == null!");
}
if (bandOffsets == null) {
throw new IllegalArgumentException("bandOffsets == null!");
}
if (bankIndices.length != bandOffsets.length) {
throw new IllegalArgumentException
("bankIndices.length != bandOffsets.length!");
}
if (dataType != DataBuffer.TYPE_BYTE &&
dataType != DataBuffer.TYPE_SHORT &&
dataType != DataBuffer.TYPE_USHORT &&
dataType != DataBuffer.TYPE_INT &&
dataType != DataBuffer.TYPE_FLOAT &&
dataType != DataBuffer.TYPE_DOUBLE) {
throw new IllegalArgumentException
("Bad value for dataType!");
}
int numBands = colorSpace.getNumComponents() +
(hasAlpha ? 1 : 0);
if (bandOffsets.length != numBands) {
throw new IllegalArgumentException
("bandOffsets.length is wrong!");
}
this.colorSpace = colorSpace;
this.bankIndices = bankIndices.clone();
this.bandOffsets = bandOffsets.clone();
this.dataType = dataType;
this.hasAlpha = hasAlpha;
this.isAlphaPremultiplied = isAlphaPremultiplied;
this.colorModel =
ImageTypeSpecifier.createComponentCM(colorSpace,
bankIndices.length,
dataType,
hasAlpha,
isAlphaPremultiplied);
int w = 1;
int h = 1;
this.sampleModel = new BandedSampleModel(dataType,
w, h,
w,
bankIndices,
bandOffsets);
}
public Banded(ColorSpace colorSpace,
int[] bankIndices,
int[] bandOffsets,
int dataType,
boolean hasAlpha,
boolean isAlphaPremultiplied) {
if (colorSpace == null) {
throw new IllegalArgumentException("colorSpace == null!");
}
if (bankIndices == null) {
throw new IllegalArgumentException("bankIndices == null!");
}
if (bandOffsets == null) {
throw new IllegalArgumentException("bandOffsets == null!");
}
if (bankIndices.length != bandOffsets.length) {
throw new IllegalArgumentException
("bankIndices.length != bandOffsets.length!");
}
if (dataType != DataBuffer.TYPE_BYTE &&
dataType != DataBuffer.TYPE_SHORT &&
dataType != DataBuffer.TYPE_USHORT &&
dataType != DataBuffer.TYPE_INT &&
dataType != DataBuffer.TYPE_FLOAT &&
dataType != DataBuffer.TYPE_DOUBLE) {
throw new IllegalArgumentException
("Bad value for dataType!");
}
int numBands = colorSpace.getNumComponents() +
(hasAlpha ? 1 : 0);
if (bandOffsets.length != numBands) {
throw new IllegalArgumentException
("bandOffsets.length is wrong!");
}
this.colorSpace = colorSpace;
this.bankIndices = (int[])bankIndices.clone();
this.bandOffsets = (int[])bandOffsets.clone();
this.dataType = dataType;
this.hasAlpha = hasAlpha;
this.isAlphaPremultiplied = isAlphaPremultiplied;
this.colorModel =
ImageTypeSpecifier.createComponentCM(colorSpace,
bankIndices.length,
dataType,
hasAlpha,
isAlphaPremultiplied);
int w = 1;
int h = 1;
this.sampleModel = new BandedSampleModel(dataType,
w, h,
w,
bankIndices,
bandOffsets);
}
/**
* {@inheritDoc}
*/
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary
parameters, int index, DecodeOptions options) throws IOException
{
DecodeResult result = new DecodeResult(new COSDictionary());
result.getParameters().addAll(parameters);
BufferedImage image = readJPX(encoded, options, result);
Raster raster = image.getRaster();
switch (raster.getDataBuffer().getDataType())
{
case DataBuffer.TYPE_BYTE:
DataBufferByte byteBuffer = (DataBufferByte) raster.getDataBuffer();
decoded.write(byteBuffer.getData());
return result;
case DataBuffer.TYPE_USHORT:
DataBufferUShort wordBuffer = (DataBufferUShort) raster.getDataBuffer();
for (short w : wordBuffer.getData())
{
decoded.write(w >> 8);
decoded.write(w);
}
return result;
case DataBuffer.TYPE_INT:
// not yet used (as of October 2018) but works as fallback
// if we decide to convert to BufferedImage.TYPE_INT_RGB
int[] ar = new int[raster.getNumBands()];
for (int y = 0; y < image.getHeight(); ++y)
{
for (int x = 0; x < image.getWidth(); ++x)
{
raster.getPixel(x, y, ar);
for (int i = 0; i < ar.length; ++i)
{
decoded.write(ar[i]);
}
}
}
return result;
default:
throw new IOException("Data type " + raster.getDataBuffer().getDataType() + " not implemented");
}
}
/**
* Creates a SampleModel with the specified width and height, that
* has a data layout compatible with this ColorModel.
* @see SampleModel
*/
public SampleModel createCompatibleSampleModel(int w, int h) {
int[] bOffs = {2, 1, 0};
return new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
w, h, 3, w*3, bOffs);
}
/**
* Sets the data for a single pixel in the specified <code>DataBuffer</code> from a primitive
* array of type TransferType. For a <code>ComponentSampleModel</code>, this will be the same as
* the data type, and samples are transferred one per array element.
*
* <p> The following code illustrates transferring data for one pixel from <code>DataBuffer
* </code> <code>db1</code>, whose storage layout is described by <code>ComponentSampleModel
* </code> <code>csm1</code>, to <code>DataBuffer</code> <code>db2</code>, whose storage layout
* is described by <code>ComponentSampleModel</code> <code>csm2</code>. The transfer will
* generally be more efficient than using getPixel/setPixel.
*
* <pre>
* ComponentSampleModel csm1, csm2;
* DataBufferInt db1, db2;
* csm2.setDataElements(x, y, csm1.getDataElements(x, y, null, db1), db2);
* </pre>
*
* Using getDataElements/setDataElements to transfer between two <code>DataBuffer</code>
* /SampleModel pairs is legitimate if the <code>SampleModel</code>s have the same number of
* bands, corresponding bands have the same number of bits per sample, and the TransferTypes are
* the same.
*
* <p>
*
* @param x The X coordinate of the pixel location.
* @param y The Y coordinate of the pixel location.
* @param obj A primitive array containing pixel data.
* @param data The <code>DataBuffer</code> containing the image data.
* @throws <code>ClassCastException</code> if obj is non-null and is not a primitive array of
* type TransferType.
* @throws <code>ArrayIndexOutOfBoundsException</code> if the coordinates are not in bounds, or
* if obj is non-null and is not large enough to hold the pixel data.
*/
@Override
public void setDataElements(final int x, final int y, final Object obj, final DataBuffer data) {
final int type = getTransferType();
final int numDataElems = getNumDataElements();
final int pixelOffset = (y * scanlineStride) + (x * pixelStride);
switch (type) {
case DataBuffer.TYPE_BYTE:
final byte[] barray = (byte[]) obj;
for (int i = 0; i < numDataElems; i++) {
data.setElem(bankIndices[i], pixelOffset + bandOffsets[i], (barray[i]) & 0xff);
}
break;
case DataBuffer.TYPE_USHORT:
final short[] usarray = (short[]) obj;
for (int i = 0; i < numDataElems; i++) {
data.setElem(bankIndices[i], pixelOffset + bandOffsets[i], (usarray[i]) & 0xffff);
}
break;
case DataBuffer.TYPE_INT:
final int[] iarray = (int[]) obj;
for (int i = 0; i < numDataElems; i++) {
data.setElem(bankIndices[i], pixelOffset + bandOffsets[i], iarray[i]);
}
break;
case DataBuffer.TYPE_SHORT:
final short[] sarray = (short[]) obj;
for (int i = 0; i < numDataElems; i++) {
data.setElem(bankIndices[i], pixelOffset + bandOffsets[i], sarray[i]);
}
break;
case DataBuffer.TYPE_FLOAT:
final float[] farray = (float[]) obj;
for (int i = 0; i < numDataElems; i++) {
data.setElemFloat(bankIndices[i], pixelOffset + bandOffsets[i], farray[i]);
}
break;
case DataBuffer.TYPE_DOUBLE:
final double[] darray = (double[]) obj;
for (int i = 0; i < numDataElems; i++) {
data.setElemDouble(bankIndices[i], pixelOffset + bandOffsets[i], darray[i]);
}
break;
default:
throw new RuntimeException("Unsupported data buffer type " + type);
}
}
public Packed(ColorSpace colorSpace,
int redMask,
int greenMask,
int blueMask,
int alphaMask, // 0 if no alpha
int transferType,
boolean isAlphaPremultiplied) {
if (colorSpace == null) {
throw new IllegalArgumentException("colorSpace == null!");
}
if (colorSpace.getType() != ColorSpace.TYPE_RGB) {
throw new IllegalArgumentException
("colorSpace is not of type TYPE_RGB!");
}
if (transferType != DataBuffer.TYPE_BYTE &&
transferType != DataBuffer.TYPE_USHORT &&
transferType != DataBuffer.TYPE_INT) {
throw new IllegalArgumentException
("Bad value for transferType!");
}
if (redMask == 0 && greenMask == 0 &&
blueMask == 0 && alphaMask == 0) {
throw new IllegalArgumentException
("No mask has at least 1 bit set!");
}
this.colorSpace = colorSpace;
this.redMask = redMask;
this.greenMask = greenMask;
this.blueMask = blueMask;
this.alphaMask = alphaMask;
this.transferType = transferType;
this.isAlphaPremultiplied = isAlphaPremultiplied;
int bits = 32;
this.colorModel =
new DirectColorModel(colorSpace,
bits,
redMask, greenMask, blueMask,
alphaMask, isAlphaPremultiplied,
transferType);
this.sampleModel = colorModel.createCompatibleSampleModel(1, 1);
}
private void checkSampleModel(SampleModel sm) {
int type = sm.getDataType();
if (type < DataBuffer.TYPE_BYTE || type > DataBuffer.TYPE_INT
|| sm.getNumBands() != 1 || sm.getSampleSize(0) != 1)
throw new IllegalArgumentException(I18N.getString("WBMPImageWriter2"));
}
@Override
public BufferedImage getImage() {
int sizeUncompressed = 0;
int size8888 = 0;
int maxWriteBuf = 2;
int maxHeight = 3;
byte[] writeBuf = new byte[maxWriteBuf];
@SuppressWarnings ("unused")
byte[] rowPointers = new byte[maxHeight];
switch (getFormat()) {
case 1:
case 513:
sizeUncompressed = getHeight() * getWidth() * 4;
break;
case 2:
sizeUncompressed = getHeight() * getWidth() * 8;
break;
case 517:
sizeUncompressed = getHeight() * getWidth() / 128;
break;
}
size8888 = getHeight() * getWidth() * 8;
if (size8888 > maxWriteBuf) {
maxWriteBuf = size8888;
writeBuf = new byte[maxWriteBuf];
}
if (getHeight() > maxHeight) {
maxHeight = getHeight();
rowPointers = new byte[maxHeight];
}
Inflater dec = new Inflater();
dec.setInput(getData(), 0, dataLength);
int declen = 0;
byte[] uc = new byte[sizeUncompressed];
try {
declen = dec.inflate(uc);
} catch (DataFormatException ex) {
throw new RuntimeException("zlib fucks", ex);
}
dec.end();
if (getFormat() == 1) {
for (int i = 0; i < sizeUncompressed; i++) {
byte low = (byte) (uc[i] & 0x0F);
byte high = (byte) (uc[i] & 0xF0);
writeBuf[(i << 1)] = (byte) (((low << 4) | low) & 0xFF);
writeBuf[(i << 1) + 1] = (byte) (high | ((high >>> 4) & 0xF));
}
} else if (getFormat() == 2) {
writeBuf = uc;
} else if (getFormat() == 513) {
for (int i = 0; i < declen; i += 2) {
byte bBits = (byte) ((uc[i] & 0x1F) << 3);
byte gBits = (byte) (((uc[i + 1] & 0x07) << 5) | ((uc[i] & 0xE0) >> 3));
byte rBits = (byte) (uc[i + 1] & 0xF8);
writeBuf[(i << 1)] = (byte) (bBits | (bBits >> 5));
writeBuf[(i << 1) + 1] = (byte) (gBits | (gBits >> 6));
writeBuf[(i << 1) + 2] = (byte) (rBits | (rBits >> 5));
writeBuf[(i << 1) + 3] = (byte) 0xFF;
}
} else if (getFormat() == 517) {
byte b = 0x00;
int pixelIndex = 0;
for (int i = 0; i < declen; i++) {
for (int j = 0; j < 8; j++) {
b = (byte) (((uc[i] & (0x01 << (7 - j))) >> (7 - j)) * 255);
for (int k = 0; k < 16; k++) {
pixelIndex = (i << 9) + (j << 6) + k * 2;
writeBuf[pixelIndex] = b;
writeBuf[pixelIndex + 1] = b;
writeBuf[pixelIndex + 2] = b;
writeBuf[pixelIndex + 3] = (byte) 0xFF;
}
}
}
}
DataBufferByte imgData = new DataBufferByte(writeBuf, sizeUncompressed);
SampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, getWidth(), getHeight(), 4, getWidth() * 4, ZAHLEN);
WritableRaster imgRaster = Raster.createWritableRaster(sm, imgData, new Point(0, 0));
BufferedImage aa = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
aa.setData(imgRaster);
return aa;
}