Java Code Examples for java.awt.Graphics2D.drawImage()

The following are Jave code examples for showing how to use drawImage() of the java.awt.Graphics2D 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: MTG-Card-Recognizer   File: ImageUtil.java   View Source Code Vote up 7 votes
public static BufferedImage getScaledImage(BufferedImage src, double fraction){
	int finalw = (int)(src.getWidth()*fraction);
	int finalh = (int)(src.getHeight()*fraction);
	double factor = 1.0d;
	if(src.getWidth() > src.getHeight()){
		factor = ((double)src.getHeight()/(double)src.getWidth());
		finalh = (int)(finalw * factor);                
	}else{
		factor = ((double)src.getWidth()/(double)src.getHeight());
		finalw = (int)(finalh * factor);
	}   

	BufferedImage resizedImg = new BufferedImage(finalw, finalh, BufferedImage.TRANSLUCENT);
	Graphics2D g2 = resizedImg.createGraphics();
	g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	g2.drawImage(src, 0, 0, finalw, finalh, null);
	g2.dispose();
	return resizedImg;
}
 
Example 2
Project: VTerminal   File: CharEdgeDetectionShader.java   View Source Code Vote up 6 votes
@Override
public BufferedImage run(final @NonNull BufferedImage image, final @NonNull AsciiCharacter character) {
    // Get the character image and filter it:
    BufferedImage charImage = swapColor(image, character.getBackgroundColor(), new Color(0, 0, 0, 0));
    charImage = new EdgeFilter().filter(charImage, null);

    // Combine image and background
    final BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    final Graphics2D gc = (Graphics2D) result.getGraphics();

    gc.setColor(character.getBackgroundColor());
    gc.fillRect(0, 0, result.getWidth(), result.getHeight());
    gc.drawImage(charImage, 1, 0, null);
    gc.drawImage(charImage, 0, 0, null);
    gc.dispose();

    return result;
}
 
Example 3
Project: VTerminal   File: AsciiTile.java   View Source Code Vote up 6 votes
/**
 * Draws the tile onto the specified context.
 *
 * @param gc
 *         The graphics context to draw with.
 *
 * @param imageCache
 *         The image cache to retrieve character images from.
 *
 * @param columnIndex
 *         The x-axis (column) coordinate where the character is to be drawn.
 *
 * @param rowIndex
 *         The y-axis (row) coordinate where the character is to be drawn.
 *
 * @throws NullPointerException
 *         If the gc or image cache are null.
 */
@Override
public void draw(final @NonNull Graphics2D gc, @NonNull final ImageCache imageCache, int columnIndex, int rowIndex) {
    if (super.updateCacheHash && super.isHidden() == false) {
        updateCacheHash();
        super.updateCacheHash = false;
    }

    final int fontWidth = imageCache.getFont().getWidth();
    final int fontHeight = imageCache.getFont().getHeight();

    columnIndex *= fontWidth;
    rowIndex *= fontHeight;

    super.getBoundingBox().setLocation(columnIndex, rowIndex);
    super.getBoundingBox().setSize(fontWidth, fontHeight);

    // Handle hidden state:
    if (super.isHidden()) {
        gc.setColor(super.getBackgroundColor());
        gc.fillRect(columnIndex, rowIndex, fontWidth, fontHeight);
    } else {
        final Image image = imageCache.retrieveFromCache(this);
        gc.drawImage(image, columnIndex, rowIndex, null);
    }
}
 
Example 4
Project: OpenJSharp   File: AffineTransformOp.java   View Source Code Vote up 6 votes
/**
 * Transforms source image using transform specified at the constructor.
 * The resulting transformed image is stored in the destination image if one
 * is provided; otherwise a new BufferedImage is created and returned. 
 *
 * @param src source image
 * @param dst destination image
 * @throws IllegalArgumentException if the source and destination image are
 *          the same
 * @return transformed source image.
 */
public final BufferedImage filter (BufferedImage src, BufferedImage dst)
{
  if (dst == src)
    throw new IllegalArgumentException("src image cannot be the same as "
                                     + "the dst image");

  // If the destination image is null, then use a compatible BufferedImage
  if (dst == null)
    dst = createCompatibleDestImage(src, null);

  Graphics2D gr = dst.createGraphics();
  gr.setRenderingHints(hints);
  gr.drawImage(src, transform, null);
  return dst;
}
 
Example 5
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 6
Project: jaer   File: RNNfilter.java   View Source Code Vote up 6 votes
private BufferedImage getScaledImage() {
    BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
    g2d.drawImage(this.image.getImage(), 0, 0, getWidth(), getHeight(), null);
    return image;
}
 
Example 7
Project: openjdk-jdk10   File: UnmanagedDrawImagePerformance.java   View Source Code Vote up 6 votes
private static long test(Image bi, Image vi, AffineTransform atfm) {
    final Polygon p = new Polygon();
    p.addPoint(0, 0);
    p.addPoint(SIZE, 0);
    p.addPoint(0, SIZE);
    p.addPoint(SIZE, SIZE);
    p.addPoint(0, 0);
    Graphics2D g2d = (Graphics2D) vi.getGraphics();
    g2d.clip(p);
    g2d.transform(atfm);
    g2d.setComposite(AlphaComposite.SrcOver);
    final long start = System.nanoTime();
    g2d.drawImage(bi, 0, 0, null);
    final long time = System.nanoTime() - start;
    g2d.dispose();
    return time;
}
 
Example 8
Project: brModelo   File: Desenhador.java   View Source Code Vote up 6 votes
public void DrawImagem(Graphics2D g) {
    BufferedImage imgB = getImagem();
    if (imgB == null) {
        return;
    }
    Rectangle rec = getBounds();
    rec.grow(-2, -2);
    if (imgres == null) {
        imgres = imgB.getScaledInstance(rec.width, rec.height, Image.SCALE_SMOOTH);
    }

    Composite originalComposite = g.getComposite();
    if (alfa != 1f) {
        int type = AlphaComposite.SRC_OVER;
        g.setComposite(AlphaComposite.getInstance(type, alfa));
    }
    Image img = imgres;
    if (isDisablePainted()) {
        img = util.Utilidades.dye(new ImageIcon(imgres), disabledColor);
    }
    
    g.drawImage(img, rec.x, rec.y, null);
    g.setComposite(originalComposite);
}
 
Example 9
Project: betacome   File: ChessPanel.java   View Source Code Vote up 6 votes
@Override
public void paint(Graphics g)
{
  Graphics2D g2d = (Graphics2D) g;
  g2d.drawImage(chessmap, 0, 0, null);
  for (int i = 0; i < 10; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      if (chessBoard[i][j] == Eveluation.NOCHESS)
      {
        continue;
      }
      int x = j * GRILLEHEIGHT + BORDERHEIGHT;
      int y = i * GRILLEWIDTH + BORDERWIDTH;
      g2d.drawImage(chessmen[chessBoard[i][j] - 1], x, y, null);
    }
  }
}
 
Example 10
Project: openjdk-jdk10   File: IncorrectClipSurface2SW.java   View Source Code Vote up 6 votes
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();
}
 
Example 11
Project: freecol   File: ImageLibrary.java   View Source Code Vote up 5 votes
public static BufferedImage createMirroredImage(Image image) {
    if(image == null)
        return null;
    final int width = image.getWidth(null);
    final int height = image.getHeight(null);
    BufferedImage result = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = result.createGraphics();
    g.drawImage(image, width, 0, -width, height, null);
    g.dispose();
    return result;
}
 
Example 12
Project: JuggleMasterPro   File: AnimatedGIFEncoder.java   View Source Code Vote up 5 votes
/**
 * Extracts image pixels into byte array "pixels"
 */
protected void getImagePixels() {
	if ((this.imgGbuffer.getWidth() != this.intGwidth) || (this.imgGbuffer.getHeight() != this.intGheight)
		|| (this.imgGbuffer.getType() != BufferedImage.TYPE_3BYTE_BGR)) {
		// create new image with right size/format
		final BufferedImage imgLbuffer = new BufferedImage(this.intGwidth, this.intGheight, BufferedImage.TYPE_3BYTE_BGR);
		final Graphics2D g = imgLbuffer.createGraphics();
		g.drawImage(this.imgGbuffer, 0, 0, null);
		this.imgGbuffer = imgLbuffer;
	}
	this.bytGpixelA = ((DataBufferByte) this.imgGbuffer.getRaster().getDataBuffer()).getData();
}
 
Example 13
Project: litiengine   File: RenderEngine.java   View Source Code Vote up 5 votes
public static void renderImage(final Graphics2D g, final Image image, final double x, final double y) {
  if (image == null) {
    return;
  }

  final AffineTransform t = AffineTransform.getTranslateInstance(x, y);
  g.drawImage(image, t, null);
}
 
Example 14
Project: GIFKR   File: GifDecoder.java   View Source Code Vote up 5 votes
private final void drawFrame(final GifFrame fr) {
	int bgCol = 0; // Current background color value
	final int[] activeColTbl; // Active color table
	if (fr.hasLocColTbl) {
		activeColTbl = fr.localColTbl;
	} else {
		activeColTbl = globalColTbl;
		if (!fr.transpColFlag) { // Only use background color if there
			bgCol = globalColTbl[bgColIndex]; // is no transparency
		}
	}
	// Handle disposal, prepare current BufferedImage for drawing
	switch (prevDisposal) {
	case 2: // Next frame draws on background canvas
		final BufferedImage bgImage = prevImg;
		final int[] px = getPixels(bgImage);
		Arrays.fill(px, bgCol); // Set background color of bgImage
		prevImg = img; // Let previous point to current, dispose current
		img = bgImage; // Let current point to background image
		break;
	case 3: // Next frame draws on previous frame, so restore previous
		System.arraycopy(getPixels(prevImg), 0, getPixels(img), 0, wh);
		break;
	default: // Next frame draws on current frame, so backup current
		System.arraycopy(getPixels(img), 0, getPixels(prevImg), 0, wh);
		break;
	}
	// Get pixels from data stream
	int[] pixels = decode(fr, activeColTbl);
	if (fr.interlaceFlag) {
		pixels = deinterlace(pixels, fr); // Rearrange pixel lines
	}
	// Draw pixels on top of current image
	final int w = fr.width, h = fr.height, numPixels = w * h;
	final BufferedImage frame = new BufferedImage(w, h, 2); // 2 = ARGB
	System.arraycopy(pixels, 0, getPixels(frame), 0, numPixels);
	final Graphics2D g = img.createGraphics();
	g.drawImage(frame, fr.left, fr.top, null);
	g.dispose();
}
 
Example 15
Project: ALTTPMenuPractice   File: ControlScreen.java   View Source Code Vote up 5 votes
public void paint(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;
	g2.scale(ZOOM, ZOOM);

	g2.drawImage(BACKGROUND, 0, 0, null);
	draw(g2, disp, 3, 1);

	if (score != null) {
		draw(g2, score, 15 - (score.getWidth() / 8), 3);
	}

	draw(g2, CARETS, 2, 7 + (selection.ordinal() * 2));
	boolean isSelected;

	isSelected = selection == Focus.MODE;
	draw(g2, isSelected ? MODE_HILITE : MODE_WORD, 2, 6);
	draw(g2, isSelected ? modeSel.wordHilite : modeSel.word, 4, 7);

	isSelected = selection == Focus.DIFFICULTY;
	draw(g2, isSelected ? DIFFICULTY_HILITE : DIFFICULTY_WORD, 2, 8);
	draw(g2, isSelected ? diffSel.wordHilite : diffSel.word, 4, 9);

	isSelected = selection == Focus.GAME;
	draw(g2, isSelected ? GAMES_HILITE : GAMES_WORD, 2, 10);
	draw(g2, isSelected ? GAME_NUMBERS_HILITE[games-1] : GAME_NUMBERS[games-1], 14, 11);

	isSelected = selection == Focus.START;
	draw(g2, isSelected ? START_HILITE : START_WORD, 7, 13);
}
 
Example 16
Project: freecol   File: ColopediaGameObjectTypePanel.java   View Source Code Vote up 5 votes
/**
 * Builds a subtree including all the given objects.
 *
 * @param root a {@code DefaultMutableTreeNode}
 * @param id The object identifier of the new branch node.
 * @param types a List of FreeColSpecObjectTypes
 */
public void addSubTrees(DefaultMutableTreeNode root, String id,
                        List<T> types) {
    String name = getName();
    ColopediaTreeItem cti = new ColopediaTreeItem(this, id, name, null);
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(cti);
    int width = ImageLibrary.ICON_SIZE.width;
    int height = ImageLibrary.ICON_SIZE.height;
    for (FreeColSpecObjectType type : types) {
        Image image = (type instanceof GoodsType)
            ? ImageLibrary.getMiscImage("image.icon." + type.getId(),
                                        ImageLibrary.ICON_SIZE)
            : (type instanceof ResourceType)
            ? ImageLibrary.getMiscImage("image.tileitem." + type.getId(),
                                        ImageLibrary.ICON_SIZE)
            : (type instanceof Nation)
            ? ImageLibrary.getMiscIconImage(type, ImageLibrary.ICON_SIZE)
            : (type instanceof BuildableType)
            ? ImageLibrary.getBuildableImage((BuildableType)type,
                                             ImageLibrary.ICON_SIZE)
            : ImageLibrary.getMiscImage(ResourceManager.REPLACEMENT_IMAGE,
                                        ImageLibrary.ICON_SIZE);
        int x = (width - image.getWidth(null)) / 2;
        int y = (height - image.getHeight(null)) / 2;
        BufferedImage centeredImage
            = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = centeredImage.createGraphics();
        g.drawImage(image, x, y, null);
        g.dispose();
        node.add(buildItem(type, new ImageIcon(centeredImage)));
    }
    root.add(node);
}
 
Example 17
Project: anagnostes   File: Normalizer.java   View Source Code Vote up 5 votes
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
	Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
	BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_BYTE_GRAY);
	Graphics2D g2d = dimg.createGraphics();
	g2d.drawImage(tmp, 0, 0, null);
	g2d.dispose();
	return dimg;
}
 
Example 18
Project: jdk8u-jdk   File: NonOpaqueDestLCDAATest.java   View Source Code Vote up 5 votes
public void render(Graphics g, int w, int h) {
    initImages(w, h);

    g.setColor(new Color(0xAD, 0xD8, 0xE6));
    g.fillRect(0, 0, w, h);

    Graphics2D g2d = (Graphics2D) g.create();
    for (Image im : images) {
        g2d.drawImage(im, 0, 0, null);
        g2d.translate(0, im.getHeight(null));
    }
}
 
Example 19
Project: ALTTPMenuPractice   File: PrettyButton.java   View Source Code Vote up 4 votes
public void paint(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;
	g2.scale(ZOOM, ZOOM);
	g2.drawImage(bgCur, 0, 0, null);
	g2.drawImage(dispCur, 8, 8, null);
}
 
Example 20
Project: freecol   File: Canvas.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public void paintComponent(Graphics g) {
    updateSizes();
    Graphics2D g2d = (Graphics2D) g;
    chatDisplay.removeOldMessages();
    Dimension size = getSize();

    if (freeColClient.isMapEditor()) {
        if (hasMap()) {
            mapViewer.displayMap(g2d);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, size.width, size.height);
        }

    } else if (freeColClient.isInGame() && hasMap()) {
        mapViewer.displayMap(g2d);

        // Grey out the map if it is not my turn (and a multiplayer game).
        if (!freeColClient.currentPlayerIsMyPlayer()) {
            if (greyLayer == null) {
                greyLayer = new GrayLayer(freeColClient);
            }
            if (greyLayer.getParent() == null) {
                add(greyLayer, JLayeredPane.DRAG_LAYER);
            }
            greyLayer.setBounds(0, 0, size.width, size.height);
            greyLayer.setPlayer(freeColClient.getGame().getCurrentPlayer());
        } else {
            if (greyLayer != null && greyLayer.getParent() != null) {
                removeFromCanvas(greyLayer);
            }
        }

        // paint chat display
        chatDisplay.display(g2d, mapViewer.getImageLibrary(), size);

    } else {
        /* main menu */
        // TODO: Check if its right to sometimes have an unfocused map
        //       ingame and end up here after clicking outside map.
        final String bgImageKey = "image.flavor.Canvas.map";
        if (ResourceManager.hasImageResource(bgImageKey)) {
            // Get the background without scaling, to avoid wasting
            // memory needlessly keeping an unbounded number of rescaled
            // versions of the largest image in FreeCol, forever.
            final Image bgImage = ResourceManager.getImage(bgImageKey);
            // Draw background image with scaling.
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(bgImage, 0, 0, size.width, size.height, this);
            String versionStr = "v. " + FreeCol.getVersion();
            Font oldFont = g2d.getFont();
            Color oldColor = g2d.getColor();
            Font newFont = oldFont.deriveFont(Font.BOLD);
            TextLayout layout = new TextLayout(versionStr, newFont,
                g2d.getFontRenderContext());
            Rectangle2D bounds = layout.getBounds();
            float x = size.width - (float) bounds.getWidth() - 5;
            float y = size.height - (float) bounds.getHeight();
            g2d.setColor(Color.white);
            layout.draw(g2d, x, y);
            g2d.setFont(oldFont);
            g2d.setColor(oldColor);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, size.width, size.height);
        }
    }
}