Java Code Examples for java.awt.image.BufferedImage.createGraphics()

The following are Jave code examples for showing how to use createGraphics() of the java.awt.image.BufferedImage class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: OffscreenRenderingTest.java   View Source Code Vote up 6 votes
private BufferedImage dumpSceneOffscreenRendering (Scene scene) {
    // validate the scene with a off-screen graphics
    BufferedImage emptyImage = new BufferedImage (1, 1, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D emptyGraphics = emptyImage.createGraphics ();
    scene.validate (emptyGraphics);
    emptyGraphics.dispose ();

    // now the scene is calculated using the emptyGraphics, all widgets should be layout and scene has its size resolved
    // paint the scene with a off-screen graphics
    Rectangle viewBounds = scene.convertSceneToView (scene.getBounds ());
    BufferedImage image = new BufferedImage (viewBounds.width, viewBounds.height, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D graphics = image.createGraphics ();
    double zoomFactor = scene.getZoomFactor ();
    graphics.scale (zoomFactor, zoomFactor);
    scene.paint (graphics);
    graphics.dispose ();

    return image;
}
 
Example 2
Project: pacman-mas   File: BoardGui.java   View Source Code Vote up 6 votes
@Override
public void paint(Graphics g)
{
    // Gets the canvas to draw in
    BufferedImage bi = new BufferedImage(
        Constant.BOARD_CELL_SIZE * board.countColumns(),
        Constant.BOARD_CELL_SIZE * board.countRows(),
        BufferedImage.TYPE_INT_RGB
    );
    
    Graphics2D canvas = bi.createGraphics();

    // Draws the game in the canvas
    for (int i = 0; i < board.countRows(); ++i)
    {
        for (int j = 0; j < board.countColumns(); ++j)
        {
            board.getCell(new Coord2D(i, j)).draw(canvas);
        }
    }
    
    // Really paints the component
    ((Graphics2D) g).drawImage(bi, 0, 0, this);
}
 
Example 3
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DTestBase.java   View Source Code Vote up 6 votes
@SuppressWarnings("SpellCheckingInspection")
void exportGraphic(String dir, String name, GraphicsExporter exporter) {
	try {
		PDDocument document = new PDDocument();

		PDFont pdArial = PDFontFactory.createDefaultFont();

		File parentDir = new File("target/test/" + dir);
		// noinspection ResultOfMethodCallIgnored
		parentDir.mkdirs();

		BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR);
		Graphics2D imageGraphics = image.createGraphics();
		exporter.draw(imageGraphics);
		imageGraphics.dispose();
		ImageIO.write(image, "PNG", new File(parentDir, name + ".png"));

		for (Mode m : Mode.values()) {
			PDPage page = new PDPage(PDRectangle.A4);
			document.addPage(page);

			PDPageContentStream contentStream = new PDPageContentStream(document, page);
			PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);
			PdfBoxGraphics2DFontTextDrawer fontTextDrawer = null;
			contentStream.beginText();
			contentStream.setStrokingColor(0, 0, 0);
			contentStream.setNonStrokingColor(0, 0, 0);
			contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
			contentStream.setTextMatrix(Matrix.getTranslateInstance(10, 800));
			contentStream.showText("Mode " + m);
			contentStream.endText();
			switch (m) {
			case FontTextIfPossible:
				fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer();
				fontTextDrawer.registerFont(
						new File("src/test/resources/de/rototor/pdfbox/graphics2d/DejaVuSerifCondensed.ttf"));
				break;
			case DefaultFontText: {
				fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
				fontTextDrawer.registerFont(
						new File("src/test/resources/de/rototor/pdfbox/graphics2d/DejaVuSerifCondensed.ttf"));
				break;
			}
			case ForceFontText:
				fontTextDrawer = new PdfBoxGraphics2DFontTextForcedDrawer();
				fontTextDrawer.registerFont(
						PdfBoxGraphics2DTestBase.class.getResourceAsStream("DejaVuSerifCondensed.ttf"));
				fontTextDrawer.registerFont("Arial", pdArial);
				break;
			case DefaultVectorized:
			default:
				break;
			}

			if (fontTextDrawer != null) {
				pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer);
			}

			exporter.draw(pdfBoxGraphics2D);
			pdfBoxGraphics2D.dispose();

			PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
			Matrix matrix = new Matrix();
			matrix.translate(0, 20);
			contentStream.transform(matrix);
			contentStream.drawForm(appearanceStream);

			matrix.scale(1.5f, 1.5f);
			matrix.translate(0, 100);
			contentStream.transform(matrix);
			contentStream.drawForm(appearanceStream);
			contentStream.close();
		}

		document.save(new File(parentDir, name + ".pdf"));
		document.close();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 4
Project: aws-photosharing-example   File: ContentFacade.java   View Source Code Vote up 6 votes
@Override
public byte[] call() throws Exception {
	BufferedImage original = ImageIO.read(_image_in);
	float ratio = (float)original.getHeight()/(float)original.getWidth();
	
	//if height > width take max_height else resize  
	int thumb_height = ratio>=1?MAX_HEIGHT:(int) (MAX_HEIGHT*ratio);
	//if width > height max_width else multiply by ratio
	int thumb_width = ratio<=1?MAX_WIDTH:(int) (MAX_WIDTH/ratio);
					
	BufferedImage result = new BufferedImage(thumb_width, thumb_height, original.getType());
	Graphics2D g = result.createGraphics();
	g.drawImage(original, 0, 0, thumb_width, thumb_height, null);
	g.dispose();
				
	ByteArrayOutputStream os = new ByteArrayOutputStream();
       ImageIO.write(result, _file_name.substring(_file_name.lastIndexOf(".")+1), os);
       
       return os.toByteArray();
}
 
Example 5
Project: openjdk-jdk10   File: WriteProgressive.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws IOException {
    Iterator witer = ImageIO.getImageWritersByFormatName("png");
    ImageWriter w = (ImageWriter)witer.next();

    File f = File.createTempFile("WriteProgressive", ".png");
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    w.setOutput(ios);

    BufferedImage bi = new BufferedImage(100, 100,
                                         BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = bi.createGraphics();
    Random r = new Random(10);
    for (int i = 0; i < 10000; i++) {
        Color c =
            new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
        g.setColor(c);
        g.fillRect(r.nextInt(100), r.nextInt(100), 1, 1);
    }

    IIOImage iioimage = new IIOImage(bi, null, null);

    ImageWriteParam param = w.getDefaultWriteParam();
    param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);

    try {
        w.write(null, iioimage, param);
    } catch (NullPointerException npe) {
        throw new RuntimeException("Got NPE during write!");
    }

    ios.close();

    BufferedImage bi2 = ImageIO.read(f);
    f.delete();

    ImageCompare.compare(bi, bi2);
}
 
Example 6
Project: betaexpansion   File: TextureWatchFX.java   View Source Code Vote up 5 votes
public TextureWatchFX(Minecraft minecraft)
{
    super(Item.pocketSundial.getIconFromDamage(0));
    isCustom = true;
    mc = minecraft;
    res = (Integer)mc.renderEngine.textureSizeIdMap.get(mc.renderEngine.getTexture("/gui/items.png"))/16;
    watchIconImageData = new int[res*res];
    dialImageData = new int[res*res];
    imageData = new byte[res*res*4];
    tileImage = 1;
    try
    {
        BufferedImage bufferedimage = ImageIO.read(mc.texturePackList.selectedTexturePack.getResourceAsStream("/gui/items.png"));
        int i = (iconIndex % 16) * res;
        int j = (iconIndex / 16) * res;
        bufferedimage.getRGB(i, j, res, res, watchIconImageData, 0, res);
        bufferedimage = ImageIO.read(mc.texturePackList.selectedTexturePack.getResourceAsStream("/misc/dial.png"));
        if(bufferedimage.getWidth() != res)
        {
        	BufferedImage tmp = new BufferedImage(res,res,BufferedImage.TYPE_4BYTE_ABGR);
        	Graphics g = tmp.createGraphics();
        	g.drawImage(bufferedimage, 0, 0, res,res, null);
        	g.dispose();
        	bufferedimage = tmp;
        }
        bufferedimage.getRGB(0, 0, res, res, dialImageData, 0, res);
    }
    catch(IOException ioexception)
    {
        ioexception.printStackTrace();
    }
}
 
Example 7
Project: jmt   File: PAResultsWindow.java   View Source Code Vote up 5 votes
BufferedImage convertType(BufferedImage src, int targetType) {
	if (src.getType() == targetType) {
		return src;
	}
	BufferedImage tgt = new BufferedImage(src.getWidth(), src.getHeight(), targetType);
	Graphics2D g = tgt.createGraphics();
	g.drawRenderedImage(src, null);
	g.dispose();
	return tgt;
}
 
Example 8
Project: Rubus   File: Convolution.java   View Source Code Vote up 5 votes
private static BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_HEIGHT, int IMG_WIDTH) {
	BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
	Graphics2D g = resizedImage.createGraphics();
	g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
	g.dispose();

	return resizedImage;
}
 
Example 9
Project: jdk8u-jdk   File: ThinLineTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
  BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
  Graphics2D g = image.createGraphics();

  g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g.setPaint(Color.WHITE);
  g.fill(new Rectangle(image.getWidth(), image.getHeight()));

  g.scale(0.5 / PIXEL, 0.5 / PIXEL);
  g.setPaint(Color.BLACK);
  g.setStroke(new BasicStroke(PIXEL));
  g.draw(new Ellipse2D.Double(PIXEL * 50, PIXEL * 50, PIXEL * 300, PIXEL * 300));

  // To visually check it
  //ImageIO.write(image, "PNG", new File(args[0]));

  boolean nonWhitePixelFound = false;
  for (int x = 0; x < 200; ++x) {
    if (image.getRGB(x, 100) != Color.WHITE.getRGB()) {
      nonWhitePixelFound = true;
      break;
    }
  }
  if (!nonWhitePixelFound) {
    throw new RuntimeException("The thin line disappeared.");
  }
}
 
Example 10
Project: TestDemo1-github   File: ThumbnailGenerator.java   View Source Code Vote up 5 votes
public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception 
{
	Image image = javax.imageio.ImageIO.read(new File(originalFile));
    
    double thumbRatio = (double)thumbWidth / (double)thumbHeight;
    int imageWidth    = image.getWidth(null);
    int imageHeight   = image.getHeight(null);
    double imageRatio = (double)imageWidth / (double)imageHeight;
    if (thumbRatio < imageRatio) 
    {
    	thumbHeight = (int)(thumbWidth / imageRatio);
    } 
    else 
    {
      	thumbWidth = (int)(thumbHeight * imageRatio);
    }
    
	if(imageWidth < thumbWidth && imageHeight < thumbHeight)
	{
		thumbWidth = imageWidth;
		thumbHeight = imageHeight;
	}
	else if(imageWidth < thumbWidth)
		thumbWidth = imageWidth;
	else if(imageHeight < thumbHeight)
		thumbHeight = imageHeight;

    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setBackground(Color.WHITE);
   	graphics2D.setPaint(Color.WHITE); 
   	graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
    
	javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile));
}
 
Example 11
Project: openjdk-jdk10   File: IncorrectClipSurface2SW.java   View Source Code Vote up 5 votes
private static BufferedImage getBufferedImage(int sw) {
    BufferedImage bi = new BufferedImage(sw, sw,
                                         BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.setColor(Color.RED);
    g2d.fillRect(0, 0, sw, sw);
    return bi;
}
 
Example 12
Project: geomapapp   File: XYGraph.java   View Source Code Vote up 5 votes
/**
 * Get the full image, not just the visible portion
 */
public BufferedImage getFullImage() {
	Rectangle r = new Rectangle (0, 0, getWidth(), getHeight());
	BufferedImage image = new BufferedImage(r.width, r.height,
			BufferedImage.TYPE_INT_RGB);
	Graphics2D g = image.createGraphics();
	g.translate( -r.x, -r.y);
	paintComponent( g, true, false );
	return image;
}
 
Example 13
Project: gate-core   File: CorpusBenchmarkIcon.java   View Source Code Vote up 5 votes
public Image getImage() {
	BufferedImage image =
           new BufferedImage(getIconWidth(), getIconHeight(),
                   BufferedImage.TYPE_INT_ARGB);
   	Graphics2D g = image.createGraphics();
   	paintIcon(null, g, 0, 0);
   	g.dispose();
   	return image;
}
 
Example 14
Project: QN-ACTR-Release   File: EnlargePDF.java   View Source Code Vote up 5 votes
BufferedImage convertType(BufferedImage src, int targetType) {
	if (src.getType() == targetType) {
		return src;
	}
	BufferedImage tgt = new BufferedImage(src.getWidth(), src.getHeight(), targetType);
	Graphics2D g = tgt.createGraphics();
	g.drawRenderedImage(src, null);
	g.dispose();
	return tgt;
}
 
Example 15
Project: opencron   File: ImageUtils.java   View Source Code Vote up 5 votes
public ImageUtils clip(int srcX, int srcY, int width, int height){
    BufferedImage newImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = newImg.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(this.dealedImage, 0, 0, width, height, srcX, srcY, srcX + width, srcY + height, null);
    this.dealedImage = newImg;
    g.dispose();

    return this;
}
 
Example 16
Project: EmoticonGIFKeyboard   File: Utils.java   View Source Code Vote up 5 votes
static BufferedImage resizeImage(BufferedImage originalImage) {
    int imageType = originalImage.getType();
    if (imageType == 0) imageType = 5;

    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, imageType);

    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
    g.dispose();

    return resizedImage;
}
 
Example 17
Project: open-rmbt   File: ImageExport.java   View Source Code Vote up 4 votes
@Override
public BufferedImage generateImage(String lang, double upload, double download, double ping, String isp, String typ, String signal, String os) throws IOException {
    String unknownString = (lang.equals("de")) ? "unbekannt" : "unknown";
    BufferedImage img = new BufferedImage(390, 130, BufferedImage.TYPE_INT_ARGB);  
    img.createGraphics();  
    Graphics2D g = (Graphics2D)img.getGraphics(); 
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    BufferedImage img2 = ImageIO.read(getClass().getResourceAsStream("forumsmall_" + lang + ".png"));
    g.drawImage(img2, null, 0, 0);
    
    //Speeds
    g.setColor(Color.black);
    g.setFont(new Font("Droid Sans", Font.BOLD, 40));
    drawCenteredString(formatNumber(download, lang), 0, 20,130,65,g);
    drawCenteredString(formatNumber(upload, lang), 130, 20,130,65,g);
    drawCenteredString(formatNumber(ping, lang), 260, 20,130,65,g);


    //ISP and other information
    g.setColor(Color.WHITE);
    g.setFont(new Font("Verdana", Font.BOLD,10));

    //de
    if (lang.equals("de")) {
        //left
        g.drawString((typ == null)?unknownString:typ, 73, 109);
        g.drawString((isp == null)?unknownString:isp, 73, 124);

        //right
        g.drawString((signal==null)?"":signal + " dBm", 270, 109);
        g.drawString((os==null)?unknownString:os, 270, 124);
        
        //hide signal caption if signal is null
        if (signal==null) {
        	g.setColor(new Color(89,178,0));
        	g.fillRect(195, 98, 71, 13);
        	
        }
        
    } 
    else { //en
        //left
        g.drawString((typ == null)?unknownString:typ, 83, 109);
        g.drawString((isp == null)?unknownString:isp, 60, 124);

        //right
        g.drawString((signal==null)?"":signal + " dBm", 290, 109);
        g.drawString((os==null)?unknownString:os, 290, 124);
        
        //hide signal caption if signal is null
        if (signal==null) {
        	g.setColor(new Color(89,178,0));
        	g.fillRect(195, 98, 90, 13);
        	
        }
    }
    
    g.dispose();
    
    return img;
}
 
Example 18
Project: StellarCrush   File: Draw.java   View Source Code Vote up 4 votes
private void init() {
    closeWindow();

    frame = new JFrame();
    frame.setUndecorated(undecorated);

    offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    onscreenImage  = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    offscreen = offscreenImage.createGraphics();
    onscreen  = onscreenImage.createGraphics();
    setXscale();
    setYscale();
    offscreen.setColor(DEFAULT_CLEAR_COLOR);
    offscreen.fillRect(0, 0, width, height);
    setPenColor();
    setPenRadius();
    setFont();
    clear();

    // add antialiasing
    RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                                              RenderingHints.VALUE_ANTIALIAS_ON);
    hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    offscreen.addRenderingHints(hints);

    //Last fill is the first to see !
    offscreen.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

    // frame stuff
    ImageIcon icon = new ImageIcon(onscreenImage);
    draw = new JLabel(icon);

    draw.addMouseListener(this);
    draw.addMouseMotionListener(this);

    frame.setContentPane(draw);
    frame.addKeyListener(this);    // JLabel cannot get keyboard focus
    frame.setResizable(false);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);            // closes all windows
    //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);      // closes only current window
    frame.setTitle(name);
    //frame.setJMenuBar(createMenuBar());
    frame.pack();
    frame.requestFocusInWindow();
    frame.setVisible(true);


}
 
Example 19
Project: openjdk-jdk10   File: InputImageTests.java   View Source Code Vote up 4 votes
Context(TestEnvironment env, Result result, int testType) {
    super(env, result);

    String content = (String)env.getModifier(contentList);
    if (content == null) {
        content = CONTENT_BLANK;
    }
    // REMIND: add option for non-opaque images
    image = createBufferedImage(size, size, content, false);

    result.setUnits(size*size);
    result.setUnitName("pixel");

    if (testType == TEST_IMAGEIO || testType == TEST_IMAGEREADER) {
        ImageReaderSpi readerspi =
            (ImageReaderSpi)env.getModifier(imageioReadFormatList);
        format = readerspi.getFileSuffixes()[0].toLowerCase();
        if (testType == TEST_IMAGEREADER) {
            seekForwardOnly = env.isEnabled(seekForwardOnlyTog);
            ignoreMetadata = env.isEnabled(ignoreMetadataTog);
            try {
                reader = readerspi.createReaderInstance();
            } catch (IOException e) {
                System.err.println("error creating reader");
                e.printStackTrace();
            }
            if (env.isEnabled(installListenerTog)) {
                reader.addIIOReadProgressListener(
                    new ReadProgressListener());
            }
        }
        if (format.equals("wbmp")) {
            // REMIND: this is a hack to create an image that the
            //         WBMPImageWriter can handle (a better approach
            //         would involve checking the ImageTypeSpecifier
            //         of the writer's default image param)
            BufferedImage newimg =
                new BufferedImage(size, size,
                                  BufferedImage.TYPE_BYTE_BINARY);
            Graphics g = newimg.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            image = newimg;
        }
    } else if (testType == TEST_TOOLKIT) {
        format = (String)env.getModifier(toolkitReadFormatList);
    } else { // testType == TEST_JPEGCODEC
        format = "jpeg";
    }

    initInput();
}
 
Example 20
Project: marathonv5   File: IconDemoApp.java   View Source Code Vote up 3 votes
/**
 * Resizes an image using a Graphics2D object backed by a BufferedImage.
 * 
 * @param srcImg
 *            - source image to scale
 * @param w
 *            - desired width
 * @param h
 *            - desired height
 * @return - the new resized image
 */
private Image getScaledImage(Image srcImg, int w, int h) {
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();
    return resizedImg;
}