0
点赞
收藏
分享

微信扫一扫

【Java】Code For Doppelgänger

免责声明:本伪代码仅供学习交流使用,请勿用作其他用途,否则后果自负。

最近重新翻看了诺兰执导的电影《致命魔术 The Prestige(2006)》,里面休·杰克曼在最后对决中使用了一招“移形换影”成功击败了贝尔,不得不说这“移形换影”真的厉害,代码上也封装一个移形换影试试吧。

下面以图片为例,使用Java编写了如下关键代码:

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ...{

    /**
     * 重塑图片
     * 
     * @param sourceFilePath 源文件路径
     * @param targetFilePath 目标文件路径
     */
    public static void reshapePic(String sourceFilePath, String targetFilePath) {
    
        BufferedImage inputImage = null;
        BufferedImage outputImage = null;
        try {
    
            // 判断目标文件所在的文件夹是否存在,若不存在先创建
            String targetFolderPath = targetFilePath.substring(0, targetFilePath.lastIndexOf("/"));
            File targetFolderFile = new File(targetFolderPath);
            if (!targetFolderFile.exists()) {
                targetFolderFile.mkdirs();
            }
    
            // 获取源图片的图像缓存
            inputImage = ImageIO.read(new File(sourceFilePath));
            // 获取图片后缀名称
            String suffix = sourceFilePath.substring(sourceFilePath.lastIndexOf(".") + 1);
    
            // 获取原图片的宽度与高度
            int inputWidth = inputImage.getWidth();
            int inputHeight = inputImage.getHeight();
    
            // 创建新的空白图片
            outputImage = new BufferedImage(inputWidth, inputHeight, BufferedImage.TYPE_INT_RGB);
    
            // 设置绘图对象,将原始图片缩放并绘制到新的图片上
            Graphics2D graphics = outputImage.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            graphics.drawImage(inputImage, 0, 0, inputWidth, inputHeight, 0, 0, inputWidth, inputHeight, null);
            graphics.dispose();
    
            // 保存新的图片
            ImageIO.write(outputImage, suffix, new File(targetFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != inputImage) {
                inputImage.flush();
            }
    
            if (null != outputImage) {
                outputImage.flush();
            }
        }
    }
}

重塑后的图片肯定没有矢量图那样高清,但一般来说肉眼很难看出差异所在。但是 Hash 值变了,这意味着什么懂的都懂。

举报

相关推荐

0 条评论