Cut out image in shape of text

后端 未结 6 2022
小鲜肉
小鲜肉 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:04

    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.

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

提交回复
热议问题