java 剪出文字形状的图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6295084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:15:06  来源:igfitidea点击:

Cut out image in shape of text

javaimageimage-processing

提问by Matt

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:

这是猫的照片:

Photo of a nice cat

一只漂亮猫的照片

and this is the text I wish to cut out:

这是我想剪掉的文字:

Text to cut out of the cat photo

从猫照片中剪下的文字

The resulting image would be this:

生成的图像将是这样的:

Resulting cut-out of the cat photo

猫照片的剪裁结果

The text image will always be black with a transparent background, and the resulting cut-out should too have a transparent background. Both input images will also be the same size.

文本图像将始终是带有透明背景的黑色,并且生成的剪切图也应具有透明背景。两个输入图像的大小也相同。

采纳答案by Martijn Courteaux

Create a new BufferedImage and iterate over all the pixels of word cat and if they are black, copy the cat-image pixels to the new image.

创建一个新的 BufferedImage 并遍历单词 cat 的所有像素,如果它们是黑色的,则将 cat-image 像素复制到新图像中。

Here is some code: (Final working code, supports anti-alias)

这是一些代码:(最终工作代码,支持抗锯齿

public static BufferedImage textEffect(BufferedImage image, BufferedImage text) {
    if (image.getWidth() != text.getWidth() ||
        image.getHeight() != text.getHeight())
    {
        throw new IllegalArgumentException("Dimensions are not the same!");
    }
    BufferedImage img = new BufferedImage(image.getWidth(),
                                          image.getHeight(),
                                          BufferedImage.TYPE_INT_ARGB_PRE);

    for (int y = 0; y < image.getHeight(); ++y) {
        for (int x = 0; x < image.getWidth(); ++x) {
           int textPixel = text.getRGB(x, y);
           int textAlpha = (textPixel & 0xFF000000);
           int sourceRGB = image.getRGB(x, y);
           int newAlpha = (int) (((textAlpha >> 24) * (sourceRGB >> 24)) / 255d);
           int imgPixel = (newAlpha << 24) |  (sourceRGB & 0x00FFFFFF);
           int rgb = imgPixel | textAlpha;
           img.setRGB(x, y, rgb);

        }
    }
    return img;
}

回答by Andrew Thompson

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);
    }
}

回答by StanislavL

Use GlyphVector. Use Fontclass

使用GlyphVector. 使用Font

public GlyphVector layoutGlyphVector(FontRenderContext frc,
                                         char[] text,
                                         int start,
                                         int limit,
                                         int flags) {

You can get outline Shapefrom glyph vector by public abstract Shape getOutline()

您可以Shape通过公共抽象形状从字形矢量中获取轮廓getOutline()

Assign the outline Shapeas a clip to your Graphicsinstance.

将轮廓Shape作为剪辑分配给您的Graphics实例。

Draw the image on the graphics.

在图形上绘制图像。

Only clipped shape will be filled.

只会填充剪切的形状。

回答by Dr. belisarius

No java here, but the needed image operations are easy to understand. In Mathematica:

这里没有java,但是需要的图像操作很容易理解。在 Mathematica 中:

enter image description here

在此处输入图片说明

回答by Gabriel Ambrósio Archanjo

You can do it in Java with just a few lines of source code, using Marvin Framework

只需几行源代码,您就可以在 Java 中使用Marvin 框架完成它

enter image description here

在此处输入图片说明

source code:

源代码:

public class CutAndFill {
    public static void main(String[] args) {
        // 1. Load images
        MarvinImage catImage = MarvinImageIO.loadImage("./res/catImage.jpg");
        MarvinImage catText = MarvinImageIO.loadImage("./res/catText.png");

        // 2. Load plug-in, set parameters and process de image
        MarvinImagePlugin combine = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.combine.combineByMask");
        combine.setAttribute("combinationImage", catImage);
        combine.setAttribute("colorMask", Color.black);
        combine.process(catText.clone(), catText);

        // 3. Save the output image.
        MarvinImageIO.saveImage(catText, "./res/catOut.jpg");
    }
}

回答by Briguy37

First, make the black portion of the "Cat" image transparent. See herefor help with this. Then, compositethat image over the picture of your favorite cat (mine is Sheeba).

首先,使“猫”图像的黑色部分透明。请参阅此处获取有关方面的帮助。然后,将该图像合成到您最喜欢的猫(我的是 Sheeba)的图片上。

The nice thing about this is you can make the transparent text image once, save it, and then apply it to all of Sheeba's family and friends!

这样做的好处是您可以制作一次透明文本图像,保存它,然后将其应用到 Sheeba 的所有家人和朋友!