下面列出了怎么用java.awt.Image的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Icon for a file, directory, or folder as it would be displayed in
* a system file browser. Example from Windows: the "M:\" directory
* displays a CD-ROM icon.
*
* The default implementation gets information from the ShellFolder class.
*
* @param f a <code>File</code> object
* @return an icon as it would be displayed by a native file chooser
* @see JFileChooser#getIcon
* @since 1.4
*/
public Icon getSystemIcon(File f) {
if (f == null) {
return null;
}
ShellFolder sf;
try {
sf = getShellFolder(f);
} catch (FileNotFoundException e) {
return null;
}
Image img = sf.getIcon(false);
if (img != null) {
return new ImageIcon(img, sf.getFolderType());
} else {
return UIManager.getIcon(f.isDirectory() ? "FileView.directoryIcon" : "FileView.fileIcon");
}
}
synchronized void updateNativeImage(Image image) {
if (isDisposed())
return;
boolean autosize = ((TrayIcon)target).isImageAutoSize();
BufferedImage bufImage = new BufferedImage(TRAY_ICON_WIDTH, TRAY_ICON_HEIGHT,
BufferedImage.TYPE_INT_ARGB);
Graphics2D gr = bufImage.createGraphics();
if (gr != null) {
try {
gr.setPaintMode();
gr.drawImage(image, 0, 0, (autosize ? TRAY_ICON_WIDTH : image.getWidth(observer)),
(autosize ? TRAY_ICON_HEIGHT : image.getHeight(observer)), observer);
createNativeImage(bufImage);
updateNativeIcon(!firstUpdate);
if (firstUpdate) firstUpdate = false;
} finally {
gr.dispose();
}
}
}
/**
* Updates the window associated with the painter.
*
* @param repaint indicates if the window should be completely repainted
* to the back buffer using {@link java.awt.Window#paintAll} before update.
*/
public void updateWindow(boolean repaint) {
boolean done = false;
Image bb = getBackBuffer(repaint);
while (!done) {
if (repaint) {
Graphics2D g = (Graphics2D)bb.getGraphics();
try {
window.paintAll(g);
} finally {
g.dispose();
}
}
done = update(bb);
if (!done) {
repaint = true;
bb = getBackBuffer(true);
}
}
}
public static void main(String[] args) throws IOException {
Image img = createTestImage();
Toolkit tk = Toolkit.getDefaultToolkit();
LUTCompareTest o = new LUTCompareTest(img);
tk.prepareImage(img, -1, -1, o);
while(!o.isImageReady()) {
synchronized(lock) {
try {
lock.wait(200);
} catch (InterruptedException e) {
}
}
}
checkResults(img);
}
@Override
public void annotate(Node node, Image badge) {
int nodeId = node.getNodeId();
if (badge == null) {
badges.remove(nodeId);
} else {
badges.put(node.getNodeId(), badge);
}
Page page = PageInspector.getDefault().getPage();
if (page instanceof WebKitPageModel) {
WebKitPageModel pageModel = (WebKitPageModel)page;
DOMNode domNode = pageModel.getNode(node.getNodeId());
if (domNode != null) {
domNode.updateIcon();
}
}
}
public static void main(String[] args) throws IOException {
Image img = createTestImage();
Toolkit tk = Toolkit.getDefaultToolkit();
LUTCompareTest o = new LUTCompareTest(img);
tk.prepareImage(img, -1, -1, o);
while(!o.isImageReady()) {
synchronized(lock) {
try {
lock.wait(200);
} catch (InterruptedException e) {
}
}
}
checkResults(img);
}
/**
* Updates the window associated with the painter.
*
* @param repaint indicates if the window should be completely repainted
* to the back buffer using {@link java.awt.Window#paintAll} before update.
*/
public void updateWindow(boolean repaint) {
boolean done = false;
Image bb = getBackBuffer(repaint);
while (!done) {
if (repaint) {
Graphics2D g = (Graphics2D)bb.getGraphics();
try {
window.paintAll(g);
} finally {
g.dispose();
}
}
done = update(bb);
if (!done) {
repaint = true;
bb = getBackBuffer(true);
}
}
}
private boolean drawHiDPIImage(Image img, int dx1, int dy1, int dx2,
int dy2, int sx1, int sy1, int sx2, int sy2,
Color bgcolor, ImageObserver observer) {
final int scale = SurfaceManager.getImageScale(img);
sx1 = Region.clipScale(sx1, scale);
sx2 = Region.clipScale(sx2, scale);
sy1 = Region.clipScale(sy1, scale);
sy2 = Region.clipScale(sy2, scale);
try {
return imagepipe.scaleImage(this, img, dx1, dy1, dx2, dy2, sx1, sy1,
sx2, sy2, bgcolor, observer);
} catch (InvalidPipeException e) {
try {
revalidateAll();
return imagepipe.scaleImage(this, img, dx1, dy1, dx2, dy2, sx1,
sy1, sx2, sy2, bgcolor, observer);
} catch (InvalidPipeException e2) {
// Still catching the exception; we are not yet ready to
// validate the surfaceData correctly. Fail for now and
// try again next time around.
return false;
}
} finally {
surfaceData.markDirty();
}
}
public void loadPreviewImage(Entity entity, Image camo, int tint, BufferedPanel bp) {
Image base = mechTileset.imageFor(entity, comp);
EntityImage entityImage = new EntityImage(base, tint, camo, bp);
Image preview = entityImage.loadPreviewImage();
BackGroundDrawer bgdPreview = new BackGroundDrawer(preview);
bp.removeBgDrawers();
bp.addBgDrawer(bgdPreview);
MediaTracker tracker = new MediaTracker(comp);
tracker.addImage(preview, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException e) {
;
}
}
void setIcon() {
String iconName = "cloud32x32.gif";
if (Util.isWindows()) {
iconName = "cloud16x16.gif";
}
String strURL = "/data/" + iconName;
try {
MediaTracker tracker = new MediaTracker(frame);
URL url = getClass().getResource(strURL);
if(url != null) {
Image image = frame.getToolkit().getImage(url);
tracker.addImage(image, 0);
tracker.waitForID(0);
frame.setIconImage(image);
} else {
}
} catch (Exception e) {
}
}
/**
* Load line clear effect images.
*/
public static void loadLineClearEffectImages() {
String skindir = NullpoMinoSwing.propConfig.getProperty("custom.skin.directory", "res");
if(imgBreak == null) {
imgBreak = new Image[BLOCK_BREAK_MAX][BLOCK_BREAK_SEGMENTS];
for(int i = 0; i < BLOCK_BREAK_MAX; i++) {
for(int j = 0; j < BLOCK_BREAK_SEGMENTS; j++) {
imgBreak[i][j] = loadImage(getURL(skindir + "/graphics/break" + i + "_" + j + ".png"));
}
}
}
if(imgPErase == null) {
imgPErase = new Image[PERASE_MAX];
for(int i = 0; i < imgPErase.length; i++) {
imgPErase[i] = loadImage(getURL(skindir + "/graphics/perase" + i + ".png"));
}
}
}
/**
* 给图片添加文字水印
* @param pressText 水印文字
* @param srcImageFile 源图像地址
* @param destImageFile 目标图像地址
* @param fontName 字体名称
* @param fontStyle 字体样式
* @param color 字体颜色
* @param fontSize 字体大小
* @param x 修正值
* @param y 修正值
* @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
*/
public final static void pressText2(String pressText, String srcImageFile,String destImageFile,
String fontName, int fontStyle, Color color, int fontSize, int x,
int y, float alpha) {
try {
File img = new File(srcImageFile);
Image src = ImageIO.read(img);
int width = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
g.setColor(color);
g.setFont(new Font(fontName, fontStyle, fontSize));
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
// 在指定坐标绘制水印文字
g.drawString(pressText, (width - (getLength(pressText) * fontSize))
/ 2 + x, (height - fontSize) / 2 + y);
g.dispose();
ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates an AttachmentBuilder based on the parameter type
*
* @param param
* runtime Parameter that abstracts the annotated java parameter
* @param setter
* specifies how the obtained value is set into the argument. Takes
* care of Holder arguments.
*/
public static EndpointArgumentsBuilder createAttachmentBuilder(ParameterImpl param, EndpointValueSetter setter) {
Class type = (Class)param.getTypeInfo().type;
if (DataHandler.class.isAssignableFrom(type)) {
return new DataHandlerBuilder(param, setter);
} else if (byte[].class==type) {
return new ByteArrayBuilder(param, setter);
} else if(Source.class.isAssignableFrom(type)) {
return new SourceBuilder(param, setter);
} else if(Image.class.isAssignableFrom(type)) {
return new ImageBuilder(param, setter);
} else if(InputStream.class==type) {
return new InputStreamBuilder(param, setter);
} else if(isXMLMimeType(param.getBinding().getMimeType())) {
return new JAXBBuilder(param, setter);
} else if(String.class.isAssignableFrom(type)) {
return new StringBuilder(param, setter);
} else {
throw new UnsupportedOperationException("Unknown Type="+type+" Attachment is not mapped.");
}
}
private static Image createTestImage() throws IOException {
BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });
ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
ImageWriteParam param = writer.getDefaultWriteParam();
writer.setOutput(ios);
writer.prepareWriteSequence(null);
writer.writeToSequence(new IIOImage(frame1, null, null), param);
writer.writeToSequence(new IIOImage(frame2, null, null), param);
writer.endWriteSequence();
writer.reset();
writer.dispose();
ios.flush();
ios.close();
return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
public boolean drawImage(Image img, int x, int y,
Color bgcolor,
ImageObserver observer) {
if (img == null) {
return true;
}
boolean result;
int srcWidth = img.getWidth(null);
int srcHeight = img.getHeight(null);
if (srcWidth < 0 || srcHeight < 0) {
result = false;
} else {
result = drawImage(img, x, y, srcWidth, srcHeight, bgcolor, observer);
}
return result;
}
public static void main(String[] args) throws IOException {
Image img = createTestImage();
Toolkit tk = Toolkit.getDefaultToolkit();
LUTCompareTest o = new LUTCompareTest(img);
tk.prepareImage(img, -1, -1, o);
while(!o.isImageReady()) {
synchronized(lock) {
try {
lock.wait(200);
} catch (InterruptedException e) {
}
}
}
checkResults(img);
}
public static void ensureImageLoaded(final Image anImage) {
final MediaTracker tracker = new MediaTracker(component);
tracker.addImage(anImage, 1);
try {
tracker.waitForAll();
tracker.removeImage(anImage);
} catch (final InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
static BufferedImage getScaledImage(JComponent component) {
Image image1x = getImage(component, 1, IMAGE_WIDTH, IMAGE_HEIGHT);
final BufferedImage image2x = new BufferedImage(
2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
final Graphics g = image2x.getGraphics();
((Graphics2D) g).scale(2, 2);
g.drawImage(image1x, 0, 0, null);
g.dispose();
return image2x;
}
/**
* Translates either a byte array or an input stream which contain
* platform-specific image data in the given format into an Image.
*/
@Override
protected Image platformImageBytesToImage(
byte[] bytes, long format) throws IOException
{
String mimeType = null;
if (format == PNG_ATOM.getAtom()) {
mimeType = "image/png";
} else if (format == JFIF_ATOM.getAtom()) {
mimeType = "image/jpeg";
} else {
// Check if an image MIME format.
try {
String nat = getNativeForFormat(format);
DataFlavor df = new DataFlavor(nat);
String primaryType = df.getPrimaryType();
if ("image".equals(primaryType)) {
mimeType = df.getPrimaryType() + "/" + df.getSubType();
}
} catch (Exception e) {
// Not an image MIME format.
}
}
if (mimeType != null) {
return standardImageBytesToImage(bytes, mimeType);
} else {
String nativeFormat = getNativeForFormat(format);
throw new IOException("Translation from " + nativeFormat +
" is not supported.");
}
}
public static BufferedImage resizeImageSmooth(BufferedImage image, int wantedWidth, int wantedHeight) {
Image scaledImage = image.getScaledInstance(wantedWidth, wantedHeight, Image.SCALE_SMOOTH);
BufferedImage imageBuff = new BufferedImage(wantedWidth, wantedHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = imageBuff.createGraphics();
g.drawImage(scaledImage, 0, 0, null, null);
g.dispose();
return imageBuff;
}
public boolean transformImage(SunGraphics2D sg, Image img,
AffineTransform atfm,
ImageObserver observer) {
if (!(img instanceof ToolkitImage)) {
transformImage(sg, img, 0, 0, atfm, sg.interpolationType);
return true;
} else {
ToolkitImage sunimg = (ToolkitImage)img;
if (!imageReady(sunimg, observer)) {
return false;
}
ImageRepresentation ir = sunimg.getImageRep();
return ir.drawToBufImage(sg, sunimg, atfm, observer);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
final Image backgroundImage = _bg;
double scaleX = getWidth() / (double) backgroundImage.getWidth(null);
double scaleY = getHeight() / (double) backgroundImage.getHeight(null);
AffineTransform xform = AffineTransform
.getScaleInstance(scaleX, scaleY);
((Graphics2D) g).drawImage(backgroundImage, xform, this);
}
/**
* Start a drag, given the <code>DragGestureEvent</code>
* that initiated the drag, the initial
* <code>Cursor</code> to use,
* the <code>Image</code> to drag,
* the offset of the <code>Image</code> origin
* from the hotspot of the <code>Cursor</code> at
* the instant of the trigger,
* the <code>Transferable</code> subject data
* of the drag, the <code>DragSourceListener</code>,
* and the <code>FlavorMap</code>.
* <P>
* @param trigger the <code>DragGestureEvent</code> that initiated the drag
* @param dragCursor the initial {@code Cursor} for this drag operation
* or {@code null} for the default cursor handling;
* see <a href="DragSourceContext.html#defaultCursor">DragSourceContext</a>
* for more details on the cursor handling mechanism during drag and drop
* @param dragImage the image to drag or {@code null}
* @param imageOffset the offset of the <code>Image</code> origin from the hotspot
* of the <code>Cursor</code> at the instant of the trigger
* @param transferable the subject data of the drag
* @param dsl the <code>DragSourceListener</code>
* @param flavorMap the <code>FlavorMap</code> to use, or <code>null</code>
* <P>
* @throws java.awt.dnd.InvalidDnDOperationException
* if the Drag and Drop
* system is unable to initiate a drag operation, or if the user
* attempts to start a drag while an existing drag operation
* is still executing
*/
public void startDrag(DragGestureEvent trigger,
Cursor dragCursor,
Image dragImage,
Point imageOffset,
Transferable transferable,
DragSourceListener dsl,
FlavorMap flavorMap) throws InvalidDnDOperationException {
SunDragSourceContextPeer.setDragDropInProgress(true);
try {
if (flavorMap != null) this.flavorMap = flavorMap;
DragSourceContextPeer dscp = Toolkit.getDefaultToolkit().createDragSourceContextPeer(trigger);
DragSourceContext dsc = createDragSourceContext(dscp,
trigger,
dragCursor,
dragImage,
imageOffset,
transferable,
dsl
);
if (dsc == null) {
throw new InvalidDnDOperationException();
}
dscp.startDrag(dsc, dsc.getCursor(), dragImage, imageOffset); // may throw
} catch (RuntimeException e) {
SunDragSourceContextPeer.setDragDropInProgress(false);
throw e;
}
}
public CGLVSyncOffScreenSurfaceData(CPlatformView pView,
CGLGraphicsConfig gc, int width, int height, Image image,
ColorModel cm, int type) {
super(pView, gc, width, height, image, cm, type);
flipSurface = CGLSurfaceData.createData(pView, image,
FLIP_BACKBUFFER);
}
public Image getIcon(int type) {
Image icon = null;
try {
URL url = new URL("nbres:/javax/swing/beaninfo/images/JTabbedPaneColor16.gif");
icon = java.awt.Toolkit.getDefaultToolkit().getImage(url);
} catch( MalformedURLException murlE ) {
}
return icon;
}
/**
* Creates a new managed image of the given width and height
* that is associated with the target Component.
*/
public Image createAcceleratedImage(Component target,
int width, int height)
{
ColorModel model = getColorModel(Transparency.OPAQUE);
WritableRaster wr =
model.createCompatibleWritableRaster(width, height);
return new OffScreenImage(target, model, wr,
model.isAlphaPremultiplied());
}
/**
* Applies a badge to an open or closed folder icon.
* <p/>
* @param badge Badge image for folder.
* @param opened Use open or closed folder.
* @return An image of the badged folder.
*/
public static Image badgeFolder(Image badge, boolean opened) {
Node folderNode = getIconDelegate();
Image folder = opened
? folderNode.getOpenedIcon(BeanInfo.ICON_COLOR_16x16)
: folderNode.getIcon(BeanInfo.ICON_COLOR_16x16);
return ImageUtilities.mergeImages(folder, badge, 7, 7);
}
/**
* Calculates and returns the image. Halts the calculation and returns
* null if the Applet is stopped during the calculation.
*/
private Image calculateImage() {
Thread me = Thread.currentThread();
int width = canvas.getSize().width;
int height = canvas.getSize().height;
int xvals[] = new int[2];
int yvals[] = new int[2];
int xmethod = XControls.getParams(xvals);
int ymethod = YControls.getParams(yvals);
int pixels[] = new int[width * height];
int c[] = new int[4]; //temporarily holds R,G,B,A information
int index = 0;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
c[0] = c[1] = c[2] = 0;
c[3] = 255;
if (xmethod < ymethod) {
applyMethod(c, xmethod, i, width, xvals);
applyMethod(c, ymethod, j, height, yvals);
} else {
applyMethod(c, ymethod, j, height, yvals);
applyMethod(c, xmethod, i, width, xvals);
}
pixels[index++] = ((c[3] << 24) | (c[0] << 16) | (c[1] << 8)
| c[2]);
}
// Poll once per row to see if we've been told to stop.
if (runner != me) {
return null;
}
}
return createImage(new MemoryImageSource(width, height,
ColorModel.getRGBdefault(), pixels, 0, width));
}
@Override
protected void renderImageXform(SunGraphics2D sg, Image img,
AffineTransform tx, int interpType,
int sx1, int sy1, int sx2, int sy2,
Color bgColor)
{
// punt to the MediaLib-based transformImage() in the superclass if:
// - bicubic interpolation is specified
// - a background color is specified and will be used
// - an appropriate TransformBlit primitive could not be found
if (interpType != AffineTransformOp.TYPE_BICUBIC) {
SurfaceData dstData = sg.surfaceData;
SurfaceData srcData =
dstData.getSourceSurfaceData(img,
sg.TRANSFORM_GENERIC,
sg.imageComp,
bgColor);
if (srcData != null && !isBgOperation(srcData, bgColor)) {
SurfaceType srcType = srcData.getSurfaceType();
SurfaceType dstType = dstData.getSurfaceType();
TransformBlit blit = TransformBlit.getFromCache(srcType,
sg.imageComp,
dstType);
if (blit != null) {
blit.Transform(srcData, dstData,
sg.composite, sg.getCompClip(),
tx, interpType,
sx1, sy1, 0, 0, sx2-sx1, sy2-sy1);
return;
}
}
}
super.renderImageXform(sg, img, tx, interpType,
sx1, sy1, sx2, sy2, bgColor);
}
static public final int[] extractARGBIntArray( final Image img )
{
final int[] pix = new int[img.getWidth(null) * img.getHeight(null)];
PixelGrabber pg = new PixelGrabber( img, 0, 0, img.getWidth(null), img.getHeight(null), pix, 0, img.getWidth(null) );
try {
pg.grabPixels();
} catch (InterruptedException ie) {}
return pix;
}