剪出文字形状的图片 [英] Cut out image in shape of text
本文介绍了剪出文字形状的图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要以另一张图像中的文字形状剪下一张图像.我认为最好用图片展示.
I need to cut out an image in the shape of the text in another image. I think it's best shown in images.
这是一张猫的照片:
这是我想剪掉的文字:
生成的图像是这样的:
文本图像将始终是带有透明背景的黑色,并且生成的剪切图也应具有透明背景.两个输入图像的大小也相同.
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 的所有像素,如果它们是黑色的,则将 cat-image 像素复制到新图像中.
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屋!
查看全文