下面列出了java.awt.image.BufferedImage#createGraphics() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void doTest(BufferedImageOp op, int stype, int dtype) {
final int size = 100;
final BufferedImage src = new BufferedImage(size, size, stype);
Graphics2D g = src.createGraphics();
g.setColor(Color.red);
g.fillRect(0, 0, size, size);
g.dispose();
final BufferedImage dst = new BufferedImage(size, size, dtype);
g = dst.createGraphics();
g.setColor(Color.blue);
g.fillRect(0, 0, size, size);
g.dispose();
op.filter(src, dst);
final int rgb = dst.getRGB(size - 1, size - 1);
System.out.printf("dst: 0x%X ", rgb);
if (rgb != 0xFFFF0000) {
throw new RuntimeException(String.format("Wrong color in dst: 0x%X", rgb));
}
}
public BufferedImage paintImage() {
if (viewers.isEmpty()) {
return null;
}
ViewComponent view = viewers.get(0);
view.view(current_model, null, null);
//Create the image
GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
BufferedImage image = configuration.createCompatibleImage(view.getWidth(), view.getHeight(), Transparency.TRANSLUCENT);
//Render the component onto the image
Graphics graphics = image.createGraphics();
view.paint(graphics);
graphics.dispose();
return image;
}
public static TexturePaint createCheckerTexture(int cs, Color color) {
int size = cs * cs;
BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setPaint(color);
g2.fillRect(0, 0, size, size);
for (int i = 0; i * cs < size; i++) {
for (int j = 0; j * cs < size; j++) {
if ((i + j) % 2 == 0) {
g2.fillRect(i * cs, j * cs, cs, cs);
}
}
}
g2.dispose();
return new TexturePaint(img, new Rectangle(size, size));
}
private static void draw(Shape clip, Shape to, Image vi, BufferedImage bi,
int scale) {
Graphics2D big = bi.createGraphics();
big.setComposite(AlphaComposite.Src);
big.setClip(clip);
Rectangle toBounds = to.getBounds();
int x1 = toBounds.x;
int y1 = toBounds.y;
int x2 = x1 + toBounds.width;
int y2 = y1 + toBounds.height;
big.drawImage(vi, x1, y1, x2, y2, 0, 0, toBounds.width / scale,
toBounds.height / scale, null);
big.dispose();
vi.flush();
}
/**
* 调整图像透明度
*
* @param image
* @param alpha
*/
public void getImageAlpha(BufferedImage image, float alpha) {
if(alpha != 1){
BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImage.createGraphics();
bufferedImage = g2.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT);
g2.dispose();
g2 = bufferedImage.createGraphics();
g2.setComposite(AlphaComposite.SrcOver.derive(alpha));
g2.drawImage(
image.getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH),
0, 0, null);
g2.dispose();
}
}
private BufferedImage convertImageIconToBufferedImage(ImageIcon icon) {
final int type = BufferedImage.TYPE_INT_ARGB;
final int width = icon.getIconWidth();
final int height = icon.getIconHeight();
final BufferedImage scratchImage = new BufferedImage(width, height, type);
final Graphics2D g2 = scratchImage.createGraphics();
g2.drawImage(icon.getImage(), 0, 0, null);
g2.dispose();
return scratchImage;
}
public static BufferedImage createTestImage(int type) {
int w = 100;
int h = 500;
BufferedImage bi = new BufferedImage(3*w, h, type);
Graphics g = bi.createGraphics();
g.setColor(Color.red);
g.fillRect(0,0,w,h);
g.setColor(Color.green);
g.fillRect(w, 0,w,h);
g.setColor(Color.blue);
g.fillRect(2*w,0,w,h);
return bi;
}
private static final BufferedImage toBufferedImage(Image img) {
// load the image
new ImageIcon(img);
BufferedImage rep = createBufferedImage(img.getWidth(null), img.getHeight(null));
Graphics g = rep.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
img.flush();
return rep;
}
private static BufferedImage createBufferedImage() {
BufferedImage image = new BufferedImage(128, 128,
BufferedImage.TYPE_4BYTE_ABGR_PRE);
Graphics2D graph = image.createGraphics();
graph.setPaintMode();
graph.setColor(Color.orange);
graph.fillRect(32, 32, 64, 64);
graph.dispose();
return image;
}
private BufferedImage produceForegroundImageIcon(BufferedImage icon) {
int imageWidth = icon.getWidth();
// According to the adaptive icon documentation, both layers are 108x108dp but only the inner
// 72x72dp appears in the masked viewport, so we shrink down the size of the image accordingly.
double iconWidth = imageWidth * 72.0 / 108.0;
// Round iconWidth value to even int for a centered png
int intIconWidth = ((int)Math.round(iconWidth / 2) * 2);
Image tmp = icon.getScaledInstance(intIconWidth, intIconWidth, Image.SCALE_SMOOTH);
int marginWidth = ((imageWidth - intIconWidth) / 2);
BufferedImage foregroundImageIcon = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = foregroundImageIcon.createGraphics();
g2.drawImage(tmp, marginWidth, marginWidth, null);
return foregroundImageIcon;
}
/**
* Scales an icon using specified scale factor
*
* @param icon icon to scale
* @param scaleFactor scale factor to use
* @return scaled icon as BuffedredImage
*/
private static BufferedImage scaleIcon(Icon icon, double scaleFactor) {
if (icon == null) {
return null;
}
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// convert icon into image
BufferedImage iconImage = gc.createCompatibleImage(w, h,
Transparency.TRANSLUCENT);
Graphics2D g = iconImage.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
// and scale it nicely
int scaledW = (int) (w * scaleFactor);
int scaledH = (int) (h * scaleFactor);
BufferedImage scaledImage = gc.createCompatibleImage(scaledW, scaledH,
Transparency.TRANSLUCENT);
g = scaledImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(iconImage, 0, 0, scaledW, scaledH, null);
g.dispose();
return scaledImage;
}
private File testWriteRGB(String format, int type)
throws IOException {
BufferedImage bi = new BufferedImage(width, height, type);
Graphics2D g = bi.createGraphics();
Color white = new Color(255, 255, 255);
Color red = new Color(255, 0, 0);
Color green = new Color(0, 255, 0);
Color blue = new Color(0, 0, 255);
g.setColor(white);
g.fillRect(0, 0, width, height);
g.setColor(red);
g.fillRect(10, 10, 20, 20);
g.setColor(green);
g.fillRect(30, 30, 20, 20);
g.setColor(blue);
g.fillRect(50, 50, 20, 20);
File file = new File("BitDepth_" + biTypeNames[type] + "." + format);
try {
ImageIO.write(bi, format, file);
} catch (RuntimeException re) {
System.out.println("Can't write a type "
+ biTypeNames[type] +
" BufferedImage!");
}
return file;
}
private static BufferedImage getImage() {
int width = 2500;
int height = new Random().nextInt(2500) + 1;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.blue);
g.fillRect(0, 0, width, height);
return image;
}
/**
* Examine the metrics captured by the
* <code>PeekGraphics</code> instance and
* if capable of directly converting this
* print job to the printer's control language
* or the native OS's graphics primitives, then
* return a <code>PSPathGraphics</code> to perform
* that conversion. If there is not an object
* capable of the conversion then return
* <code>null</code>. Returning <code>null</code>
* causes the print job to be rasterized.
*/
protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
PrinterJob printerJob,
Printable painter,
PageFormat pageFormat,
int pageIndex) {
PSPathGraphics pathGraphics;
PeekMetrics metrics = peekGraphics.getMetrics();
/* If the application has drawn anything that
* out PathGraphics class can not handle then
* return a null PathGraphics.
*/
if (forcePDL == false && (forceRaster == true
|| metrics.hasNonSolidColors()
|| metrics.hasCompositing())) {
pathGraphics = null;
} else {
BufferedImage bufferedImage = new BufferedImage(8, 8,
BufferedImage.TYPE_INT_RGB);
Graphics2D bufferedGraphics = bufferedImage.createGraphics();
boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;
pathGraphics = new PSPathGraphics(bufferedGraphics, printerJob,
painter, pageFormat, pageIndex,
canRedraw);
}
return pathGraphics;
}
/**
* Constructor.
* @param imageWidth the width
* @param imageHeight the height
*/
public AwtRenderingBackend(final int imageWidth, final int imageHeight) {
id_ = ID_GENERATOR_++;
if (LOG.isDebugEnabled()) {
LOG.debug("[" + id_ + "] AwtRenderingBackend(" + imageWidth + ", " + imageHeight + ")");
}
image_ = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
graphics2D_ = image_.createGraphics();
graphics2D_.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D_.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics2D_.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
// reset
fillColor_ = Color.black;
strokeColor_ = Color.black;
lineWidth_ = 1;
transformation_ = new AffineTransform();
setGlobalAlpha(1.0);
graphics2D_.setClip(null);
graphics2D_.setBackground(new Color(0f, 0f, 0f, 0f));
graphics2D_.setColor(Color.black);
graphics2D_.clearRect(0, 0, imageWidth, imageHeight);
subPaths_ = new ArrayList<>();
savedStates_ = new ArrayDeque<>();
}
/**
* Draws the chart with a null info object to make sure that no exceptions
* are thrown (a problem that was occurring at one point).
*/
@Test
public void testDrawWithNullInfo() {
try {
BufferedImage image = new BufferedImage(200 , 100,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
this.chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null,
null);
g2.dispose();
}
catch (Exception e) {
fail("No exception should be triggered.");
}
}
private static BufferedImage getSourceGold(GraphicsConfiguration gc,
int size) {
final BufferedImage bi = gc.createCompatibleImage(size, size);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, size, size);
g2d.dispose();
return bi;
}
static BufferedImage resize(BufferedImage image, int width, int height) {
final BufferedImage resized = new BufferedImage(width, 64, image.getType());
final Graphics2D g = resized.createGraphics();
g.addRenderingHints(ImmutableMap.of(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR));
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
return resized;
}
/**
* <p>Returns a thumbnail of a source image. <code>newSize</code> defines
* the length of the longest dimension of the thumbnail. The other
* dimension is then computed according to the dimensions ratio of the
* original picture.</p>
* <p>This method favors speed over quality. When the new size is less than
* half the longest dimension of the source image,
* {@link #createThumbnail(BufferedImage, int)} or
* {@link #createThumbnail(BufferedImage, int, int)} should be used instead
* to ensure the quality of the result without sacrificing too much
* performance.</p>
*
* @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
* @see #createThumbnail(java.awt.image.BufferedImage, int)
* @see #createThumbnail(java.awt.image.BufferedImage, int, int)
* @param image the source image
* @param newSize the length of the largest dimension of the thumbnail
* @return a new compatible <code>BufferedImage</code> containing a
* thumbnail of <code>image</code>
* @throws IllegalArgumentException if <code>newSize</code> is larger than
* the largest dimension of <code>image</code> or <= 0
*/
public static BufferedImage createThumbnailFast(BufferedImage image,
int newSize) {
float ratio;
int width = image.getWidth();
int height = image.getHeight();
if (width > height) {
if (newSize >= width) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image width");
} else if (newSize <= 0) {
throw new IllegalArgumentException("newSize must" +
" be greater than 0");
}
ratio = (float) width / (float) height;
width = newSize;
height = (int) (newSize / ratio);
} else {
if (newSize >= height) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image height");
} else if (newSize <= 0) {
throw new IllegalArgumentException("newSize must" +
" be greater than 0");
}
ratio = (float) height / (float) width;
height = newSize;
width = (int) (newSize / ratio);
}
BufferedImage temp = createCompatibleImage(image, width, height);
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
g2.dispose();
return temp;
}
/**
* <p>Returns a thumbnail of a source image.</p>
* <p>This method offers a good trade-off between speed and quality.
* The result looks better than
* {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
* the new size is less than half the longest dimension of the source
* image, yet the rendering speed is almost similar.</p>
*
* @see #createThumbnailFast(java.awt.image.BufferedImage, int)
* @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
* @see #createThumbnail(java.awt.image.BufferedImage, int)
* @param image the source image
* @param newWidth the width of the thumbnail
* @param newHeight the height of the thumbnail
* @return a new compatible <code>BufferedImage</code> containing a
* thumbnail of <code>image</code>
* @throws IllegalArgumentException if <code>newWidth</code> is larger than
* the width of <code>image</code> or if code>newHeight</code> is larger
* than the height of <code>image or if one the dimensions is not > 0</code>
*/
public static BufferedImage createThumbnail(BufferedImage image,
int newWidth, int newHeight) {
int width = image.getWidth();
int height = image.getHeight();
if (newWidth >= width || newHeight >= height) {
throw new IllegalArgumentException("newWidth and newHeight cannot" +
" be greater than the image" +
" dimensions");
} else if (newWidth <= 0 || newHeight <= 0) {
throw new IllegalArgumentException("newWidth and newHeight must" +
" be greater than 0");
}
BufferedImage thumb = image;
do {
if (width > newWidth) {
width /= 2;
if (width < newWidth) {
width = newWidth;
}
}
if (height > newHeight) {
height /= 2;
if (height < newHeight) {
height = newHeight;
}
}
BufferedImage temp = createCompatibleImage(image, width, height);
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
g2.dispose();
thumb = temp;
} while (width != newWidth || height != newHeight);
return thumb;
}