下面列出了java.awt.Image#getWidth() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private ImageIcon scale(final ImageIcon image) {
final Image img = image.getImage();
final Dimension ssize = Toolkit.getDefaultToolkit().getScreenSize();
final int ow = img.getWidth(null);
final int oh = img.getHeight(null);
// screens are usually wide..
final int w = ssize.width - 20;
final int h = ssize.height - 100;
if ((ow >= w) || (oh >= h)) {
return new ImageIcon(img.getScaledInstance(w, h,
Image.SCALE_AREA_AVERAGING));
} else {
return image;
}
}
static void testToolkitMultiResolutionImageLoad(Image image) throws Exception {
MediaTracker tracker = new MediaTracker(new JPanel());
tracker.addImage(image, 0);
tracker.waitForID(0);
if (tracker.isErrorAny()) {
throw new RuntimeException("Error during image loading");
}
tracker.removeImage(image, 0);
testImageLoaded(image);
int w = image.getWidth(null);
int h = image.getHeight(null);
Image resolutionVariant = ((MultiResolutionImage) image)
.getResolutionVariant(2 * w, 2 * h);
if (image == resolutionVariant) {
throw new RuntimeException("Resolution variant is not loaded");
}
testImageLoaded(resolutionVariant);
}
/**
* Constructs an <code>ImageGraphicAttribute</code> from the specified
* <code>Image</code>. The point
* (<code>originX</code>, <code>originY</code>) in the
* <code>Image</code> appears at the origin of the
* <code>ImageGraphicAttribute</code> within the text.
* @param image the <code>Image</code> rendered by this
* <code>ImageGraphicAttribute</code>.
* This object keeps a reference to <code>image</code>.
* @param alignment one of the alignments from this
* <code>ImageGraphicAttribute</code>
* @param originX the X coordinate of the point within
* the <code>Image</code> that appears at the origin of the
* <code>ImageGraphicAttribute</code> in the text line.
* @param originY the Y coordinate of the point within
* the <code>Image</code> that appears at the origin of the
* <code>ImageGraphicAttribute</code> in the text line.
*/
public ImageGraphicAttribute(Image image,
int alignment,
float originX,
float originY) {
super(alignment);
// Can't clone image
// fImage = (Image) image.clone();
fImage = image;
fImageWidth = image.getWidth(null);
fImageHeight = image.getHeight(null);
// ensure origin is in Image?
fOriginX = originX;
fOriginY = originY;
}
/**
* Constructs an <code>ImageGraphicAttribute</code> from the specified
* <code>Image</code>. The point
* (<code>originX</code>, <code>originY</code>) in the
* <code>Image</code> appears at the origin of the
* <code>ImageGraphicAttribute</code> within the text.
* @param image the <code>Image</code> rendered by this
* <code>ImageGraphicAttribute</code>.
* This object keeps a reference to <code>image</code>.
* @param alignment one of the alignments from this
* <code>ImageGraphicAttribute</code>
* @param originX the X coordinate of the point within
* the <code>Image</code> that appears at the origin of the
* <code>ImageGraphicAttribute</code> in the text line.
* @param originY the Y coordinate of the point within
* the <code>Image</code> that appears at the origin of the
* <code>ImageGraphicAttribute</code> in the text line.
*/
public ImageGraphicAttribute(Image image,
int alignment,
float originX,
float originY) {
super(alignment);
// Can't clone image
// fImage = (Image) image.clone();
fImage = image;
fImageWidth = image.getWidth(null);
fImageHeight = image.getHeight(null);
// ensure origin is in Image?
fOriginX = originX;
fOriginY = originY;
}
private synchronized void waitForDimensions(Image img) {
mHeight = img.getHeight(this);
mWidth = img.getWidth(this);
while (!badImage && (mWidth < 0 || mHeight < 0)) {
try {
Thread.sleep(50);
} catch(InterruptedException e) {
// do nothing.
}
mHeight = img.getHeight(this);
mWidth = img.getWidth(this);
}
if (badImage) {
mHeight = 0;
mWidth = 0;
}
}
/**
* Draws an image, applying a transform from image space into user space
* before drawing.
* The transformation from user space into device space is done with
* the current transform in the Graphics2D.
* The given transformation is applied to the image before the
* transform attribute in the Graphics2D state is applied.
* The rendering attributes applied include the clip, transform,
* and composite attributes. Note that the result is
* undefined, if the given transform is noninvertible.
* @param img The image to be drawn.
* This method does nothing if {@code img} is null.
* @param xform The transformation from image space into user space.
* @param obs The image observer to be notified as more of the image
* is converted.
* @see #transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @see #setClip
*/
public boolean drawImage(Image img,
AffineTransform xform,
ImageObserver obs) {
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 = drawImageToPlatform(img, xform, null,
0, 0, srcWidth, srcHeight, false);
}
return result;
}
public static void main(String[] args) throws Exception {
if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
return;
}
String icon = "NSImage://NSApplicationIcon";
final Image image = Toolkit.getDefaultToolkit().getImage(icon);
if (!(image instanceof MultiResolutionImage)) {
throw new RuntimeException("Icon does not have resolution variants!");
}
MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image;
int width = 0;
int height = 0;
for (Image resolutionVariant : multiResolutionImage.getResolutionVariants()) {
int rvWidth = resolutionVariant.getWidth(null);
int rvHeight = resolutionVariant.getHeight(null);
if (rvWidth < width || rvHeight < height) {
throw new RuntimeException("Resolution variants are not sorted!");
}
width = rvWidth;
height = rvHeight;
}
}
public static void main(String[] args) throws Exception {
if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
return;
}
String icon = "NSImage://NSApplicationIcon";
final Image image = Toolkit.getDefaultToolkit().getImage(icon);
if (!(image instanceof MultiResolutionImage)) {
throw new RuntimeException("Icon does not have resolution variants!");
}
MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image;
int width = 0;
int height = 0;
for (Image resolutionVariant : multiResolutionImage.getResolutionVariants()) {
int rvWidth = resolutionVariant.getWidth(null);
int rvHeight = resolutionVariant.getHeight(null);
if (rvWidth < width || rvHeight < height) {
throw new RuntimeException("Resolution variants are not sorted!");
}
width = rvWidth;
height = rvHeight;
}
}
private static Color getImageColor(final Object renderingHint, Image image,
double configScale, double graphicsScale) {
int width = image.getWidth(null);
int height = image.getHeight(null);
TestSurfaceData surface = new TestSurfaceData(width, height, configScale);
SunGraphics2D g2d = new SunGraphics2D(surface,
Color.BLACK, Color.BLACK, null);
g2d.setRenderingHint(KEY_RESOLUTION_VARIANT, renderingHint);
g2d.scale(graphicsScale, graphicsScale);
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return surface.getColor(width / 2, height / 2);
}
/**
* Converts an AWT image to SWT.
*
* @param image the image (<code>null</code> not permitted).
*
* @return Image data.
*/
public static ImageData convertAWTImageToSWT(Image image) {
ParamChecks.nullNotPermitted(image, "image");
int w = image.getWidth(null);
int h = image.getHeight(null);
if (w == -1 || h == -1) {
return null;
}
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return convertToSWT(bi);
}
public static BufferedImage imageToBufferedImage(Image image) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
return bufferedImage;
}
/**
* removes the Transparency of an {@link Image}
*
* @param image
* @return {@link BufferedImage} without Transparency
*/
public static BufferedImage removeTransparency(Image image) {
int w = image.getWidth(null);
int h = image.getHeight(null);
BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi2.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
g.drawImage(image, 0, 0, null);
g.dispose();
return bi2;
}
/**
* removes the Transparency of an {@link Image}
*
* @param image
* @return {@link BufferedImage} without Transparency
*/
public static BufferedImage removeTransparency(Image image) {
int w = image.getWidth(null);
int h = image.getHeight(null);
BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi2.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
g.drawImage(image, 0, 0, null);
g.dispose();
return bi2;
}
/** Creates new form JigSawEditor */
public HolesEditorPanel(Options options, Holes shaper, Dimension previewDim, Image img, BoxBase previewBb) {
this.options = options;
this.shaper = shaper;
this.img = img;
this.previewDim = previewDim;
initializing = true;
currentShape = shaper.getNumCells() + 1;
previewArea = new Rectangle(img == null ? previewDim : new Dimension(img.getWidth(this), img.getHeight(this)));
this.previewBb = previewBb;
initMembers();
initComponents();
customizeComponents();
pdp = new PolygonDrawPanel(img == null ? (int) (previewDim.getWidth()) : img.getWidth(this),
img == null ? ((int) previewDim.getHeight()) : img.getHeight(this), this, (img == null));
pdp.addPointListener(this);
if (previewPanel != null) {
((PreviewPanel) previewPanel).vp.addMouseMotionListener(pdp);
((PreviewPanel) previewPanel).vp.addMouseListener(pdp);
}
initializing = false;
shapeChanged();
}
/**
* Draws an image at x,y in nonblocking mode with a solid background
* color and a callback object.
*/
public boolean drawImage(Image img, int x, int y, Color bg,
ImageObserver observer) {
if (img == null) {
return true;
}
if (isHiDPIImage(img)) {
final int imgW = img.getWidth(null);
final int imgH = img.getHeight(null);
return drawHiDPIImage(img, x, y, x + imgW, y + imgH, 0, 0, imgW,
imgH, bg, observer);
}
try {
return imagepipe.copyImage(this, img, x, y, bg, observer);
} catch (InvalidPipeException e) {
try {
revalidateAll();
return imagepipe.copyImage(this, img, x, y, bg, 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();
}
}
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) {
if (SurfaceManager.getImageScale(img) != 1) { // Volatile Image
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);
} else if (img instanceof MultiResolutionImage) {
// get scaled destination image size
int width = img.getWidth(observer);
int height = img.getHeight(observer);
Image resolutionVariant = getResolutionVariant(
(MultiResolutionImage) img, width, height,
dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
if (resolutionVariant != img && resolutionVariant != null) {
// recalculate source region for the resolution variant
ImageObserver rvObserver = MultiResolutionToolkitImage.
getResolutionVariantObserver(img, observer,
width, height, -1, -1);
int rvWidth = resolutionVariant.getWidth(rvObserver);
int rvHeight = resolutionVariant.getHeight(rvObserver);
if (0 < width && 0 < height && 0 < rvWidth && 0 < rvHeight) {
float widthScale = ((float) rvWidth) / width;
float heightScale = ((float) rvHeight) / height;
sx1 = Region.clipScale(sx1, widthScale);
sy1 = Region.clipScale(sy1, heightScale);
sx2 = Region.clipScale(sx2, widthScale);
sy2 = Region.clipScale(sy2, heightScale);
observer = rvObserver;
img = resolutionVariant;
}
}
}
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();
}
}
/**
* Override paint method
* @see javax.swing.JComponent#paint(java.awt.Graphics)
*/
public void paint(Graphics inG)
{
super.paint(inG);
if (_photo != null)
{
// read thumbnail in separate thread
if (_thumbnail == null && !_loadingImage && !_loadFailed)
{
_loadingImage = true;
new Thread(this).start();
}
// if loading, display message
if (_loadingImage)
{
inG.setColor(Color.BLACK);
inG.drawString(LOADING_STRING, 10, 30);
}
else if (_thumbnail != null && !_loadFailed)
{
// Copy scaled, smoothed (and rotated) image into scaled
int usableWidth = getParent().getWidth()-10;
int usableHeight = (_inPanel?usableWidth:getHeight()-10);
Image scaled = ImageUtils.rotateImage(_thumbnail, usableWidth, usableHeight, _photo.getRotationDegrees());
int scaleWidth = scaled.getWidth(null);
int scaleHeight = scaled.getHeight(null);
// Draw scaled / rotated image to component
int horizOffset = (getWidth() - scaleWidth) / 2;
int vertOffset = (getHeight() - scaleHeight) / 2;
inG.drawImage(scaled, horizOffset, vertOffset, scaleWidth, scaleHeight, null);
// Special resize behaviour when locked inside details panel
if (_inPanel && (getHeight() < getWidth() || getHeight() > usableWidth))
{
Dimension newsize = new Dimension(usableWidth, usableWidth);
setPreferredSize(newsize);
setSize(newsize);
invalidate();
// Schedule a relayout because the size has changed
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {Thread.sleep(200);} catch (InterruptedException e) {}
getParent().getParent().getParent().validate();
}
});
}
}
}
}
protected void startDrag(Transferable trans,
long[] formats, Map formatMap) {
long nativeCtxtLocal = 0;
nativeCtxtLocal = createDragSource(getTrigger().getComponent(),
trans,
getTrigger().getTriggerEvent(),
getTrigger().getSourceAsDragGestureRecognizer().getSourceActions(),
formats,
formatMap);
if (nativeCtxtLocal == 0) {
throw new InvalidDnDOperationException("failed to create native peer");
}
int[] imageData = null;
Point op = null;
Image im = getDragImage();
int imageWidth = -1;
int imageHeight = -1;
if (im != null) {
//image is ready (partial images are ok)
try{
imageWidth = im.getWidth(null);
imageHeight = im.getHeight(null);
if (imageWidth < 0 || imageHeight < 0) {
throw new InvalidDnDOperationException("drag image is not ready");
}
//We could get an exception from user code here.
//"im" and "dragImageOffset" are user-defined objects
op = getDragImageOffset(); //op could not be null here
BufferedImage bi = new BufferedImage(
imageWidth,
imageHeight,
BufferedImage.TYPE_INT_ARGB);
bi.getGraphics().drawImage(im, 0, 0, null);
//we can get out-of-memory here
imageData = ((DataBufferInt)bi.getData().getDataBuffer()).getData();
} catch (Throwable ex) {
throw new InvalidDnDOperationException("drag image creation problem: " + ex.getMessage());
}
}
//We shouldn't have user-level exceptions since now.
//Any exception leads to corrupted D'n'D state.
setNativeContext(nativeCtxtLocal);
WDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(trans);
if (imageData != null) {
doDragDrop(
getNativeContext(),
getCursor(),
imageData,
imageWidth, imageHeight,
op.x, op.y);
} else {
doDragDrop(
getNativeContext(),
getCursor(),
null,
-1, -1,
0, 0);
}
}
/**
* Draw an image, applying a transform from image space into user space
* before drawing.
* The transformation from user space into device space is done with
* the current transform in the Graphics2D.
* The given transformation is applied to the image before the
* transform attribute in the Graphics2D state is applied.
* The rendering attributes applied include the clip, transform,
* paint or color and composite attributes. Note that the result is
* undefined, if the given transform is non-invertible.
* @param img The image to be drawn.
* @param xform The transformation from image space into user space.
* @param observer The image observer to be notified on the image producing
* progress.
* @see #transform
* @see #setComposite
* @see #setClip
*/
public boolean drawImage(Image img,
AffineTransform xform,
ImageObserver observer) {
if (img == null) {
return true;
}
if (xform == null || xform.isIdentity()) {
return drawImage(img, 0, 0, null, observer);
}
if (isHiDPIImage(img)) {
final int w = img.getWidth(null);
final int h = img.getHeight(null);
final AffineTransform tx = new AffineTransform(transform);
transform(xform);
boolean result = drawHiDPIImage(img, 0, 0, w, h, 0, 0, w, h, null,
observer);
transform.setTransform(tx);
invalidateTransform();
return result;
}
try {
return imagepipe.transformImage(this, img, xform, observer);
} catch (InvalidPipeException e) {
try {
revalidateAll();
return imagepipe.transformImage(this, img, xform, 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 static int[] getSize(int width, Image image) {
int targetWidth = image.getWidth(null);
int targetHeight = image.getHeight(null);
long height = Math.round((targetHeight * width) / (targetWidth * 1.00f));
return new int[] { width, Integer.parseInt(String.valueOf(height)) };
}