Cut out image in shape of text

后端 未结 6 2068
小鲜肉
小鲜肉 2020-11-22 11:15

I need to cut out an image in the shape of the text in another image. I think it\'s best shown in images.

This is a photo of a cat:

6条回答
  •  余生分开走
    2020-11-22 12:05

    Cat text

    import java.awt.*;
    import java.awt.font.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.Rectangle2D;
    import javax.imageio.ImageIO;
    import java.net.URL;
    import java.io.File;
    
    class PictureText {
    
        public static void main(String[] args) throws Exception {
            URL url = new URL("http://i.stack.imgur.com/Nqf3H.jpg");
            BufferedImage originalImage = ImageIO.read(url);
            final BufferedImage textImage = new BufferedImage(
                originalImage.getWidth(),
                originalImage.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = textImage.createGraphics();
            FontRenderContext frc = g.getFontRenderContext();
            Font font = new Font(Font.SANS_SERIF, Font.BOLD, 250);
            GlyphVector gv = font.createGlyphVector(frc, "Cat");
            Rectangle2D box = gv.getVisualBounds();
            int xOff = 25+(int)-box.getX();
            int yOff = 80+(int)-box.getY();
            Shape shape = gv.getOutline(xOff,yOff);
            g.setClip(shape);
            g.drawImage(originalImage,0,0,null);
            g.setClip(null);
            g.setStroke(new BasicStroke(2f));
            g.setColor(Color.BLACK);
            g.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g.draw(shape);
    
            g.dispose();
    
            File file = new File("cat-text.png");
            ImageIO.write(textImage,"png",file);
            Desktop.getDesktop().open(file);
        }
    }
    

提交回复
热议问题