剪出图像的文字形状 [英] Cut out image in shape of text

查看:138
本文介绍了剪出图像的文字形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在另一张图片中剪切出文字形状的图像。我认为它最好显示在图像中。

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

这是一张猫的照片:

这是我希望的文字剪出:

and this is the text I wish to cut out:

结果图像如下:

文字图片将始终为黑色,背景为透明,并且由此产生的切口也应该具有透明背景。两个输入图像也将具有相同的大小。

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.

推荐答案

创建一个新的BufferedImage并迭代单词cat的所有像素,如果它们是黑色的,将猫图像像素复制到新图像。

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.

以下是一些代码:(最终工作代码,支持反别名

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

这篇关于剪出图像的文字形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆