下面列出了怎么用java.awt.image.WritableRaster的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Converts a rendered image to a {@code BufferedImage}. This utility
* method has come from a forum post by Jim Moore at:
* <p>
* <a href="http://www.jguru.com/faq/view.jsp?EID=114602">
* http://www.jguru.com/faq/view.jsp?EID=114602</a>
*
* @param img the rendered image.
*
* @return A buffered image.
*/
private static BufferedImage convertRenderedImage(RenderedImage img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
ColorModel cm = img.getColorModel();
int width = img.getWidth();
int height = img.getHeight();
WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
Hashtable properties = new Hashtable();
String[] keys = img.getPropertyNames();
if (keys != null) {
for (int i = 0; i < keys.length; i++) {
properties.put(keys[i], img.getProperty(keys[i]));
}
}
BufferedImage result = new BufferedImage(cm, raster,
isAlphaPremultiplied, properties);
img.copyData(raster);
return result;
}
/**
* Calculates and returns band histograms of a BufferedImage w/o a need to extract the raster
*
* @param raster
* @param width
* @param height
* @param iNumBins
* @return
*/
public static int[][] getChannelHistograms(WritableRaster raster, int width, int height, int iNumBins) {
int[][] histograms = new int[raster.getNumBands()][iNumBins];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
for (int band = 0; band < raster.getNumBands(); band++) {
histograms[band][raster.getSample(col, row, band)]++;
}
}
}
return histograms;
}
public synchronized Raster getRaster(int x, int y, int w, int h) {
WritableRaster t = savedTile;
if (t == null || w > t.getWidth() || h > t.getHeight()) {
t = getColorModel().createCompatibleWritableRaster(w, h);
IntegerComponentRaster icr = (IntegerComponentRaster) t;
Arrays.fill(icr.getDataStorage(), color);
// Note - markDirty is probably unnecessary since icr is brand new
icr.markDirty();
if (w <= 64 && h <= 64) {
savedTile = t;
}
}
return t;
}
/**
* <p>Writes a rectangular area of pixels in the destination <code>BufferedImage</code>. Calling this method on an
* image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code>
* will unmanage the image.</p>
*
* @param img the destination image
* @param x the x location at which to start storing pixels
* @param y the y location at which to start storing pixels
* @param w the width of the rectangle of pixels to store
* @param h the height of the rectangle of pixels to store
* @param pixels an array of pixels, stored as integers
* @throws IllegalArgumentException is <code>pixels</code> is non-null and of length < w*h
*/
static void setPixels(BufferedImage img,
int x, int y, int w, int h, byte[] pixels) {
if (pixels == null || w == 0 || h == 0) {
return;
} else if (pixels.length < w * h) {
throw new IllegalArgumentException("pixels array must have a length >= w*h");
}
int imageType = img.getType();
if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
WritableRaster raster = img.getRaster();
raster.setDataElements(x, y, w, h, pixels);
} else {
throw new IllegalArgumentException("Only type BYTE_GRAY is supported");
}
}
/**
* Draw a coverage data image tile from the flat array of coverage data
* values of length tileWidth * tileHeight where each coverage data value is
* at: (y * tileWidth) + x
*
* @param griddedTile
* gridded tile
* @param values
* coverage data values of length tileWidth * tileHeight
* @param tileWidth
* tile width
* @param tileHeight
* tile height
* @return coverage data image tile
*/
public BufferedImage drawTile(GriddedTile griddedTile, Double[] values,
int tileWidth, int tileHeight) {
BufferedImage image = createImage(tileWidth, tileHeight);
WritableRaster raster = image.getRaster();
for (int x = 0; x < tileWidth; x++) {
for (int y = 0; y < tileHeight; y++) {
Double value = values[(y * tileWidth) + x];
short pixelValue = getPixelValue(griddedTile, value);
setPixelValue(raster, x, y, pixelValue);
}
}
return image;
}
private static void crashTest() {
Raster src = createSrcRaster();
WritableRaster dst = createDstRaster();
ConvolveOp op = createConvolveOp(ConvolveOp.EDGE_NO_OP);
try {
op.filter(src, dst);
} catch (ImagingOpException e) {
/*
* The test pair of source and destination rasters
* may cause failure of the medialib convolution routine,
* so this exception is expected.
*
* The JVM crash is the only manifestation of this
* test failure.
*/
}
System.out.println("Test PASSED.");
}
public static void convertScreenShot2(IntBuffer bgraBuf, BufferedImage out){
WritableRaster wr = out.getRaster();
DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
int[] cpuArray = db.getData();
bgraBuf.clear();
bgraBuf.get(cpuArray);
// int width = wr.getWidth();
// int height = wr.getHeight();
//
// // flip the components the way AWT likes them
// for (int y = 0; y < height / 2; y++){
// for (int x = 0; x < width; x++){
// int inPtr = (y * width + x);
// int outPtr = ((height-y-1) * width + x);
// int pixel = cpuArray[inPtr];
// cpuArray[inPtr] = cpuArray[outPtr];
// cpuArray[outPtr] = pixel;
// }
// }
}
/**
* Create a {@link WritableRaster} from a int array.
*
* @param width the width of the raster to create.
* @param height the height of the raster to create.
* @param pixels the array of data.
* @return the produced raster.
*/
public static WritableRaster createWritableRasterFromArray( int width, int height, int[] pixels ) {
WritableRaster writableRaster = createWritableRaster(width, height, null, null, null);
int index = 0;
for( int row = 0; row < height; row++ ) {
for( int col = 0; col < width; col++ ) {
double value = (double) pixels[index];
if (value == 0) {
value = doubleNovalue;
}
writableRaster.setSample(col, row, 0, value);
index++;
}
}
return writableRaster;
}
private static void crashTest() {
Raster src = createSrcRaster();
WritableRaster dst = createDstRaster();
ConvolveOp op = createConvolveOp(ConvolveOp.EDGE_NO_OP);
try {
op.filter(src, dst);
} catch (ImagingOpException e) {
/*
* The test pair of source and destination rasters
* may cause failure of the medialib convolution routine,
* so this exception is expected.
*
* The JVM crash is the only manifestation of this
* test failure.
*/
}
System.out.println("Test PASSED.");
}
private static Float getSplitRatio(final BufferedImage image, int axis) {
WritableRaster raster = image.getRaster();
double[] sdOfDerivationX = ImageFinderUtil.createSdOfDerivation(raster, axis);
int width = image.getWidth();
int rangeStart = (int) Math.floor(width * (LOOK_RATIO - MAX_DIST_RATIO / 2));
int rangeEnd = (int) Math.ceil(width * (LOOK_RATIO + MAX_DIST_RATIO / 2));
double min = Double.MAX_VALUE;
int minIndex = -1;
for (int i = rangeStart; i < rangeEnd; i++) {
if (sdOfDerivationX[i] < min) {
min = sdOfDerivationX[i];
minIndex = i;
}
}
return ((float) minIndex) / width;
}
public synchronized Raster getRaster(int x, int y, int w, int h) {
WritableRaster t = savedTile;
if (t == null || w > t.getWidth() || h > t.getHeight()) {
t = getColorModel().createCompatibleWritableRaster(w, h);
IntegerComponentRaster icr = (IntegerComponentRaster) t;
Arrays.fill(icr.getDataStorage(), color);
// Note - markDirty is probably unnecessary since icr is brand new
icr.markDirty();
if (w <= 64 && h <= 64) {
savedTile = t;
}
}
return t;
}
public void runTest(Object ctx, int numReps) {
ImageOpTests.Context ictx = (ImageOpTests.Context)ctx;
RasterOp op = ictx.rasterOp;
Raster src = ictx.rasSrc;
WritableRaster dst = ictx.rasDst;
if (ictx.touchSrc) {
Graphics gSrc = ictx.bufSrc.getGraphics();
do {
gSrc.fillRect(0, 0, 1, 1);
op.filter(src, dst);
} while (--numReps > 0);
} else {
do {
op.filter(src, dst);
} while (--numReps > 0);
}
}
/**
* Whether we can return the data buffer's bank data without performing any
* copy or conversion operations.
*/
private static boolean canUseBankDataDirectly(final WritableRaster r,
final int transferType, final Class<? extends DataBuffer> dataBufferClass)
{
final int tt = r.getTransferType();
if (tt != transferType) return false;
final DataBuffer buffer = r.getDataBuffer();
if (!dataBufferClass.isInstance(buffer)) return false;
final SampleModel model = r.getSampleModel();
if (!(model instanceof ComponentSampleModel)) return false;
final ComponentSampleModel csm = (ComponentSampleModel) model;
final int pixelStride = csm.getPixelStride();
if (pixelStride != 1) return false;
final int w = r.getWidth();
final int scanlineStride = csm.getScanlineStride();
if (scanlineStride != w) return false;
final int c = r.getNumBands();
final int[] bandOffsets = csm.getBandOffsets();
if (bandOffsets.length != c) return false;
for (int i = 0; i < bandOffsets.length; i++) {
if (bandOffsets[i] != 0) return false;
}
for (int i = 0; i < bandOffsets.length; i++) {
if (bandOffsets[i] != i) return false;
}
return true;
}
public Any(WritableRaster srcRas, ColorModel cm,
AffineTransform xform, int maxw, boolean filter)
{
super(cm, xform, srcRas.getWidth(), srcRas.getHeight(), maxw);
this.srcRas = srcRas;
this.filter = filter;
}
/**
* Constructs an OffScreenImage given a color model and tile,
* for offscreen rendering to be used with a given component.
* The component is used to obtain the foreground color, background
* color and font.
*/
public OffScreenImage(Component c, ColorModel cm, WritableRaster raster,
boolean isRasterPremultiplied)
{
super(cm, raster, isRasterPremultiplied, null);
this.c = c;
initSurface(raster.getWidth(), raster.getHeight());
}
private static BufferedImage createCustomBuffer() {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ColorModel cm = new ComponentColorModel(cs, false, false,
Transparency.OPAQUE, DataBuffer.TYPE_FLOAT);
WritableRaster wr = cm.createCompatibleWritableRaster(width, height);
return new BufferedImage(cm, wr, false, null);
}
public BufferedImage getOpaqueRGBImage() {
if (bimage.getType() == BufferedImage.TYPE_INT_ARGB) {
int w = bimage.getWidth();
int h = bimage.getHeight();
int size = w * h;
// Note that we steal the data array here, but only for reading...
DataBufferInt db = (DataBufferInt)biRaster.getDataBuffer();
int[] pixels = SunWritableRaster.stealData(db, 0);
for (int i = 0; i < size; i++) {
if ((pixels[i] >>> 24) != 0xff) {
return bimage;
}
}
ColorModel opModel = new DirectColorModel(24,
0x00ff0000,
0x0000ff00,
0x000000ff);
int bandmasks[] = {0x00ff0000, 0x0000ff00, 0x000000ff};
WritableRaster opRaster = Raster.createPackedRaster(db, w, h, w,
bandmasks,
null);
try {
BufferedImage opImage = createImage(opModel, opRaster,
false, null);
return opImage;
} catch (Exception e) {
return bimage;
}
}
return bimage;
}
/**
* 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,
dataBuffer,
new Rectangle(x0, y0, width, height),
new Point(sampleModelTranslateX+deltaX,
sampleModelTranslateY+deltaY),
this);
}
public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
{
final Composer c;
if ( srcColorModel.getNumColorComponents() > 1 )
{
if ( srcColorModel.hasAlpha() )
c = new ARGB2ARGB();
else
c = new RGB2ARGB();
}
else
c = new Gray2ARGB();
return new CompositeContext()
{
private Composer composer = c;
public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
{
final int[] srcPixel = new int[ 4 ];
final int[] dstInPixel = new int[ 4 ];
for ( int x = 0; x < dstOut.getWidth(); x++ )
{
for ( int y = 0; y < dstOut.getHeight(); y++ )
{
src.getPixel( x, y, srcPixel );
dstIn.getPixel( x, y, dstInPixel );
composer.compose( srcPixel, dstInPixel, alpha );
dstOut.setPixel( x, y, dstInPixel );
}
}
}
public void dispose()
{}
};
}
@Override
public WritableRaster createCompatibleWritableRaster(final int w,
final int h)
{
return Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, w, h, 1,
null);
}
/**
* 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
* DataBuffers as the parent raster, but using different offsets.
* @param x X offset.
* @param y Y offset.
* @param width Width of the subraster.
* @param height Height 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 raster");
}
if (y < this.minY) {
throw new RasterFormatException("y lies outside raster");
}
if ((x+width < x) || (x+width > this.width + this.minX)) {
throw new RasterFormatException("(x + width) is outside raster") ;
}
if ((y+height < y) || (y+height > this.height + this.minY)) {
throw new RasterFormatException("(y + height) is outside raster");
}
SampleModel sm;
if (bandList != null)
sm = sampleModel.createSubsetSampleModel(bandList);
else
sm = sampleModel;
int deltaX = x0 - x;
int deltaY = y0 - y;
return new ByteBandedRaster(sm,
dataBuffer,
new Rectangle(x0,y0,width,height),
new Point(sampleModelTranslateX+deltaX,
sampleModelTranslateY+deltaY),
this);
}
public void runTest(Object octx, int numReps) {
final Context ctx = (Context)octx;
final ColorConvertOp op = ctx.op_rst;
final Raster src = ctx.rsrc;
WritableRaster dst = ctx.rdst;
do {
try {
dst = op.filter(src, dst);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
public static Raster testRasterTransform(Raster src, WritableRaster dst,
AffineTransform transform) {
AffineTransformOp op =
new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
return op.filter(src, dst);
}
/**
* Scales the image using the Java2D API, with the resultant image having the
* given color model.
*/
public static BufferedImage scale2D(final BufferedImage image,
final int width, final int height, final Object hint, final ColorModel cm)
{
final WritableRaster raster = cm.createCompatibleWritableRaster(width,
height);
final boolean isRasterPremultiplied = cm.isAlphaPremultiplied();
return copyScaled(image, new BufferedImage(cm, raster,
isRasterPremultiplied, null), hint);
}
/**
* Creates a 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 raster");
}
if (y < this.minY) {
throw new RasterFormatException("y lies outside raster");
}
if ((x+width < x) || (x+width > this.minX + this.width)) {
throw new RasterFormatException("(x + width) is outside raster");
}
if ((y+height < y) || (y+height > this.minY + this.height)) {
throw new RasterFormatException("(y + height) is outside raster");
}
SampleModel sm;
if (bandList != null)
sm = sampleModel.createSubsetSampleModel(bandList);
else
sm = sampleModel;
int deltaX = x0 - x;
int deltaY = y0 - y;
return new IntegerComponentRaster(sm,
dataBuffer,
new Rectangle(x0,y0,width,height),
new Point(sampleModelTranslateX+deltaX,
sampleModelTranslateY+deltaY),
this);
}
/**
* Creates a 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 raster");
}
if (y < this.minY) {
throw new RasterFormatException("y lies outside raster");
}
if ((x+width < x) || (x+width > this.minX + this.width)) {
throw new RasterFormatException("(x + width) is outside raster");
}
if ((y+height < y) || (y+height > this.minY + this.height)) {
throw new RasterFormatException("(y + height) is outside raster");
}
SampleModel sm;
if (bandList != null)
sm = sampleModel.createSubsetSampleModel(bandList);
else
sm = sampleModel;
int deltaX = x0 - x;
int deltaY = y0 - y;
return new IntegerInterleavedRaster(sm,
dataBuffer,
new Rectangle(x0,y0,width,height),
new Point(sampleModelTranslateX+deltaX,
sampleModelTranslateY+deltaY),
this);
}
/**
* Constructs an OffScreenImage given a color model and tile,
* for offscreen rendering to be used with a given component.
* The component is used to obtain the foreground color, background
* color and font.
*/
public OffScreenImage(Component c, ColorModel cm, WritableRaster raster,
boolean isRasterPremultiplied)
{
super(cm, raster, isRasterPremultiplied, null);
this.c = c;
initSurface(raster.getWidth(), raster.getHeight());
}
public WritableRaster makeRaster(int w, int h) {
WritableRaster ras = makeByteRaster(srcRas, w, h);
ByteInterleavedRaster biRas = (ByteInterleavedRaster) ras;
outData = biRas.getDataStorage();
outSpan = biRas.getScanlineStride();
outOff = biRas.getDataOffset(0);
return ras;
}
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);
}
public WritableRaster makeRaster(int w, int h) {
WritableRaster ras = makeByteRaster(srcRas, w, h);
ByteInterleavedRaster biRas = (ByteInterleavedRaster) ras;
outData = biRas.getDataStorage();
outSpan = biRas.getScanlineStride();
outOff = biRas.getDataOffset(0);
return ras;
}