下面列出了java.awt.image.BufferedImage#getGraphics() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void lessGraphArea1() throws Exception {
//test using an absolute time axis that doesn't fit everything.
Instant start = TimeScalesTest.create(2013, 4, 5, 11, 13, 10, 900);
TimeSeriesDataset data = TimeSeriesDatasets.timeSeriesOf(new ArrayDouble(1,2,3,4,5,6),
Arrays.asList(start,
start.plus(Duration.ofMillis(10000)),
start.plus(Duration.ofMillis(20000)),
start.plus(Duration.ofMillis(30000)),
start.plus(Duration.ofMillis(40000)),
start.plus(Duration.ofMillis(50000))));
BufferedImage image = new BufferedImage(300, 200, BufferedImage.TYPE_3BYTE_BGR);
LineTimeGraph2DRenderer renderer = new LineTimeGraph2DRenderer(300, 200);
renderer.update(new LineTimeGraph2DRendererUpdate().interpolation(InterpolationScheme.PREVIOUS_VALUE)
.timeAxisRange(TimeAxisRanges.absolute(TimeInterval.between(start,
start.plus(Duration.ofMillis(30000)))))
.axisRange(AxisRanges.fixed(0, 10)));
Graphics2D graphics = (Graphics2D) image.getGraphics();
renderer.draw(graphics, data);
ImageAssert.compareImages("lineTimeGraph.lessGraphArea.1", image);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Find")) {
BufferedImage back = ImageUtils.createCompatibleBufferedImage(3, 3, BufferedImage.TRANSLUCENT);
Graphics g = back.getGraphics();
g.setColor(new Color(120, 120, 120, 120));
g.fillRect(0, 0, back.getWidth(), back.getHeight());
g.setColor(new Color(120, 120, 120));
g.drawLine(0, 0, 3, 3);
g.dispose();
TexturePaint paint = new TexturePaint(back, new Rectangle2D.Double(0, 0, back.getWidth(), back.getHeight()));
jxFilterPane.setBackgroundPainter(new MattePainter(paint));
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < jConquersTable.getColumnCount(); i++) {
TableColumnExt col = jConquersTable.getColumnExt(i);
if (col.isVisible() && !col.getTitle().equals("Entfernung") && !col.getTitle().equals("Dorfpunkte")) {
model.addElement(col.getTitle());
}
}
jXColumnList.setModel(model);
jXColumnList.setSelectedIndex(0);
jxFilterPane.setVisible(true);
}
}
@Test
public void extraGraphAreaDegenerate2() throws Exception {
//test going backwards in time with no extra graph area. Essentially,
//our data points extend the whole x axis range, but the last data point
//has x value less than other data points
Instant start = TimeScalesTest.create(2013, 4, 5, 11, 13, 3, 900);
TimeSeriesDataset data = TimeSeriesDatasets.timeSeriesOf(new ArrayDouble(1,2,3,4,5,-1),
Arrays.asList(start,
start.plus(Duration.ofMillis(3000)),
start.plus(Duration.ofMillis(6000)),
start.plus(Duration.ofMillis(8500)),
start.plus(Duration.ofMillis(12500)),
start.plus(Duration.ofMillis(1500))));
BufferedImage image = new BufferedImage(300, 200, BufferedImage.TYPE_3BYTE_BGR);
LineTimeGraph2DRenderer renderer = new LineTimeGraph2DRenderer(300, 200);
renderer.update(new LineTimeGraph2DRendererUpdate().interpolation(InterpolationScheme.PREVIOUS_VALUE)
.timeAxisRange(TimeAxisRanges.absolute(TimeInterval.between(start,
start.plus(Duration.ofMillis(12500))))));
Graphics2D graphics = (Graphics2D) image.getGraphics();
renderer.draw(graphics, data);
ImageAssert.compareImages("lineTimeGraph.extraGraphArea.degenerate.2", image);
}
private static Image createTrayIconImage() {
/**
* Create a small image of a red circle to use as the icon for the tray icon
*/
int trayIconImageSize = 32;
final BufferedImage trayImage = new BufferedImage(trayIconImageSize, trayIconImageSize, BufferedImage.TYPE_INT_ARGB);
final Graphics2D trayImageGraphics = (Graphics2D) trayImage.getGraphics();
trayImageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
trayImageGraphics.setColor(new Color(255, 255, 255, 0));
trayImageGraphics.fillRect(0, 0, trayImage.getWidth(), trayImage.getHeight());
trayImageGraphics.setColor(Color.red);
int trayIconImageInset = 4;
trayImageGraphics.fillOval(trayIconImageInset,
trayIconImageInset,
trayImage.getWidth() - 2 * trayIconImageInset,
trayImage.getHeight() - 2 * trayIconImageInset);
trayImageGraphics.setColor(Color.darkGray);
trayImageGraphics.drawOval(trayIconImageInset,
trayIconImageInset,
trayImage.getWidth() - 2 * trayIconImageInset,
trayImage.getHeight() - 2 * trayIconImageInset);
return trayImage;
}
/**
* Tests INT_ARGB LosslessFactoryTest#createFromImage(PDDocument document, BufferedImage image)
*
* @throws java.io.IOException
*/
@Test
public void testCreateLosslessFromImageINT_ARGB() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));
// create an ARGB image
int w = image.getWidth();
int h = image.getHeight();
BufferedImage argbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics ag = argbImage.getGraphics();
ag.drawImage(image, 0, 0, null);
ag.dispose();
for (int x = 0; x < argbImage.getWidth(); ++x)
{
for (int y = 0; y < argbImage.getHeight(); ++y)
{
argbImage.setRGB(x, y, (argbImage.getRGB(x, y) & 0xFFFFFF) | ((y / 10 * 10) << 24));
}
}
PDImageXObject ximage = LosslessFactory.createFromImage(argbImage);
validate(ximage, 8, argbImage.getWidth(), argbImage.getHeight(), "png",
PDDeviceRGB.INSTANCE.getName());
checkIdent(argbImage, ximage.getImage());
checkIdentRGB(argbImage, ximage.getOpaqueImage());
assertNotNull(ximage.getSoftMask());
validate(ximage.getSoftMask(), 8, argbImage.getWidth(), argbImage.getHeight(), "png",
PDDeviceGray.INSTANCE.getName());
assertTrue(colorCount(ximage.getSoftMask().getImage()) > image.getHeight() / 10);
doWritePDF(document, ximage, testResultsDir, "intargb.pdf");
}
@Test
public void manyLinesStress() throws Exception {
List<Point2DDataset> data = largeDataset();
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = (Graphics2D) image.getGraphics();
LineGraph2DRenderer renderer = new LineGraph2DRenderer(100, 100);
renderer.update(renderer.newUpdate().interpolation(InterpolationScheme.LINEAR)
.xAxisRange(AxisRanges.auto(0.0))
.yAxisRange(AxisRanges.auto(0.0)));
renderer.draw(g, data);
//Compares to correct image
ImageAssert.compareImages("lineGraph2D.manyLinesStress", image);
}
static void generateImage(int scale) throws Exception {
BufferedImage image = new BufferedImage(
scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(scale == 1 ? COLOR_1X : COLOR_2X);
g.fillRect(0, 0, scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT);
File file = new File(scale == 1 ? IMAGE_NAME_1X : IMAGE_NAME_2X);
ImageIO.write(image, "png", file);
}
@Test
public void excessGraphs() throws Exception {
List<Point2DDataset>data = linear5Dataset();
BufferedImage image = new BufferedImage(640, 480, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = (Graphics2D) image.getGraphics();
MultiAxisLineGraph2DRenderer renderer = new MultiAxisLineGraph2DRenderer(640,480);
renderer.update(renderer.newUpdate().separateAreas(true));
renderer.draw(g, data);
//Compares to correct image
ImageAssert.compareImages("multiYAxisGraph2D.split.excessGraphs", image);
}
BufferedImage getSplat(int id, int damage)
{
//Get a copy of the hitsplat to get a clean one each time
final BufferedImage rawSplat = spriteManager.getSprite(id, 0);
if (rawSplat == null)
{
return null;
}
final BufferedImage splat = new BufferedImage(
rawSplat.getColorModel(),
rawSplat.copyData(null),
rawSplat.getColorModel().isAlphaPremultiplied(),
null);
final Graphics g = splat.getGraphics();
g.setFont(FontManager.getRunescapeSmallFont());
// Align the text in the centre of the hitsplat
final FontMetrics metrics = g.getFontMetrics();
final String text = String.valueOf(damage);
final int x = (splat.getWidth() - metrics.stringWidth(text)) / 2;
final int y = (splat.getHeight() - metrics.getHeight()) / 2 + metrics.getAscent();
g.setColor(Color.BLACK);
g.drawString(String.valueOf(damage), x + 1, y + 1);
g.setColor(Color.WHITE);
g.drawString(String.valueOf(damage), x, y);
return splat;
}
public int getHeight() {
if (heightCash == -1) {
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setFont(diagram.getFont());
FontMetrics metrics = g.getFontMetrics();
String nodeText = diagram.getNodeText();
heightCash = nodeText.split("\n").length * metrics.getHeight() + INSET;
}
return heightCash;
}
public static void testFontOfSize(float sz, Object textHint) {
BufferedImage bi = new BufferedImage(200, 200,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) bi.getGraphics();
g2.setFont(g2.getFont().deriveFont(sz));
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textHint);
g2.drawString("test", 100, 100);
}
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;
}
/**
* 画像を結合し、1枚の画像にします。
*
* @param images 結合前の画像群
* @return 結合後の画像
*/
public static BufferedImage merge(List<List<BufferedImage>> images) {
// 結合後の画像サイズを調べる
int totalHeight = 0;
int totalWidth = -1;
for (List<BufferedImage> lineImages : images) {
totalHeight += lineImages.get(0).getHeight();
if (totalWidth < 0) {
int width = 0;
for (BufferedImage image : lineImages) {
width += image.getWidth();
}
totalWidth = width;
}
}
// 画像の結合
LOG.trace("(Merge) new image[{}, {}]", totalWidth, totalHeight);
BufferedImage screenshot = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
Graphics graphics = screenshot.getGraphics();
int nextTop = 0;
for (List<BufferedImage> lineImage : images) {
int imgHeight = -1;
int nextLeft = 0;
for (BufferedImage img : lineImage) {
graphics.drawImage(img, nextLeft, nextTop, null);
nextLeft += img.getWidth();
if (imgHeight < 0) {
imgHeight = img.getHeight();
}
}
nextTop += imgHeight;
}
return screenshot;
}
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { //压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
//插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
private static Image createImage(final int length, final Color color) {
final BufferedImage image = new BufferedImage(length, length,
BufferedImage.TYPE_INT_ARGB_PRE);
final Graphics graphics = image.getGraphics();
graphics.setColor(color);
graphics.fillRect(0, 0, length, length);
graphics.dispose();
return image;
}
@Test
public void startValueEndNaNCubic() throws Exception {
Point2DDataset data = startValueEndNaNDataset();
BufferedImage image = new BufferedImage(300, 200, BufferedImage.TYPE_3BYTE_BGR);
LineGraph2DRenderer renderer = new LineGraph2DRenderer(300, 200);
renderer.update(renderer.newUpdate().interpolation(InterpolationScheme.CUBIC));
Graphics2D graphics = (Graphics2D) image.getGraphics();
renderer.draw(graphics, data);
ImageAssert.compareImages("lineGraph2D.cubic.NaN.startValueEndNaN", image);
}
public static Image getJailCompleteImage(ImageInfoReader imageInfoReader) {
BufferedImage image = createImage(BuildingDimensions.JAIL);
Graphics2D g2 = (Graphics2D) image.getGraphics();
World world = new WorldImpl(20, 20, null, null);
IdList ids = generateJail(0, 0, world, 1f);
drawIds(imageInfoReader, g2, world, ids);
g2.dispose();
return image;
}
public static void main(final String[] args) throws Exception {
//Frame initialisation
final BufferedImage graphicsProducer =
new BufferedImage(BufferedImage.TYPE_INT_ARGB, 1, 1);
final Graphics g = graphicsProducer.getGraphics();
frame.setLayout(new GridLayout());
frame.add(buttonStub);
frame.add(canvasStub);
frame.add(checkboxStub);
frame.add(choiceStub);
frame.add(lwComponentStub);
frame.add(containerStub);
frame.add(labelStub);
frame.add(listStub);
frame.add(panelStub);
frame.add(scrollbarStub);
frame.add(scrollPaneStub);
frame.add(textAreaStub);
frame.add(textFieldStub);
frame.setSize(new Dimension(500, 500));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
sleep();
//Check results.
validation();
//Reset all flags to 'false'.
initPaintedFlags();
//Tested method.
frame.paintAll(g);
sleep();
//Check results.
validation();
cleanup();
}
public static void renderPage(String pdfPath, String outPath, int pageNumber, Rectangle area,
boolean drawTextChunks, boolean drawSpreadsheets, boolean drawRulings, boolean drawIntersections,
boolean drawColumns, boolean drawCharacters, boolean drawArea, boolean drawCells,
boolean drawUnprocessedRulings, boolean drawProjectionProfile, boolean drawClippingPaths,
boolean drawDetectedTables) throws IOException {
PDDocument document = PDDocument.load(new File(pdfPath));
ObjectExtractor oe = new ObjectExtractor(document);
Page page = oe.extract(pageNumber + 1);
if (area != null) {
page = page.getArea(area);
}
PDPage p = document.getPage(pageNumber);
BufferedImage image = Utils.pageConvertToImage(p, 72, ImageType.RGB);
Graphics2D g = (Graphics2D) image.getGraphics();
if (drawTextChunks) {
debugTextChunks(g, page);
}
if (drawSpreadsheets) {
debugSpreadsheets(g, page);
}
if (drawRulings) {
debugRulings(g, page);
}
if (drawIntersections) {
debugIntersections(g, page);
}
if (drawColumns) {
debugColumns(g, page);
}
if (drawCharacters) {
debugCharacters(g, page);
}
if (drawArea) {
g.setColor(Color.ORANGE);
drawShape(g, area);
}
if (drawCells) {
debugCells(g, area, page);
}
if (drawUnprocessedRulings) {
debugNonCleanRulings(g, page);
}
if (drawProjectionProfile) {
debugProjectionProfile(g, page);
}
if (drawClippingPaths) {
// TODO: Enable when oe.clippingPaths is done
//drawShapes(g, oe.clippingPaths,
// new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] { 3f }, 0f));
}
if (drawDetectedTables) {
debugDetectedTables(g, page);
}
document.close();
ImageIO.write(image, "jpg", new File(outPath));
}
/**
* Implement of transform copy area for 1.4
*
* @param image The image to copy
* @param x The x position to copy to
* @param y The y position to copy to
* @param width The width of the image
* @param height The height of the image
* @param dx The transform on the x axis
* @param dy The transform on the y axis
*/
private void copyArea(BufferedImage image, int x, int y, int width, int height, int dx, int dy) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.drawImage(image.getSubimage(x, y, width, height),x+dx,y+dy,null);
}