Mat*_*att 43 java image image-processing
我需要在另一个图像中剪切出文本形状的图像.我认为它最好显示在图像中.
这是一张猫的照片:
这是我要删除的文字:
生成的图像是这样的:
文本图像将始终为黑色并具有透明背景,并且生成的剪切图案也应具有透明背景.两个输入图像也将具有相同的大小.
And*_*son 33
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*aux 21
创建一个新的BufferedImage并迭代单词cat的所有像素,如果它们是黑色,则将cat-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;
}
Run Code Online (Sandbox Code Playgroud)
Sta*_*avL 15
使用GlyphVector
.使用Font
课程
public GlyphVector layoutGlyphVector(FontRenderContext frc,
char[] text,
int start,
int limit,
int flags) {
Run Code Online (Sandbox Code Playgroud)
您可以Shape
通过公共抽象Shape从字形向量中获取轮廓getOutline()
将轮廓指定Shape
为Graphics
实例的剪辑.
在图形上绘制图像.
只会填充剪裁的形状.