在Java中将文本转换为图像

时间:2014-05-09 15:12:44

标签: java graphics2d cryptoapi

我正在用Java编写Visual Cryptography项目的代码。我们想为随机令牌(字母数字字符串)创建两个共享图像,这样当两个图像重叠时,令牌将被显示。 现在 - 甚至在视觉加密部分开始之前,我试图找到一种方法将这个字母数字标记转换为图像,并且不知道从哪里开始。有什么建议?谢谢!

3 个答案:

答案 0 :(得分:2)

public class TextToGraphicConverter {



  public static void main(String[] args) throws Exception {
        BufferedImage image = new TextToGraphicConverter().convertTextToGraphic("my text", new Font("Arial", Font.PLAIN, 18));
        //write BufferedImage to file
        ImageIO.write(image, "png", new File("path-to-file.png"));
    }

    public BufferedImage convertTextToGraphic(String text, Font font) {

        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();

        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int width = fm.stringWidth(text);
        int height = fm.getHeight();
        g2d.dispose();

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setFont(font);
        fm = g2d.getFontMetrics();
        g2d.setColor(Color.BLACK);
        g2d.drawString(text, 0, fm.getAscent());
        g2d.dispose();
        return img;
    }
}

答案 1 :(得分:0)

首先创建一个BufferedImage对象,获取其Graphics上下文,调用Graphics.drawString()将您的令牌转换为图像数据,然后将BufferedImage写入磁盘。

答案 2 :(得分:0)

我不会知道太多,但我猜他会像这样接近它:

String string="something";
Byte[] byteArray=string.getbytes();

//split the byte array into two one for each image. probably want something different than what i did.
int count=0
Byte[] bytes1=new Bytes[byteArray.length];
Byte[] bytes2=new Bytes[byteArray.length];
for(Byte b:byteArray){
bytes1[count]=b*0.2;

bytes2[count]=b*0.8;
count++;
}
//init images
BufferedImage img1 = new BufferedImage(bytes1.length, 1,BufferedImage.TYPE_INT_RGB);
BufferedImage img2 = new BufferedImage(bytes1.length, 1,BufferedImage.TYPE_INT_RGB);


//put bytes into pixels as int
int count=0;
for(Byte b: bytes1){
img1.setRGB(0, count, (int)b);
count++;}

count=0;
for(Byte b: bytes2){
img2.setRGB(0, count, (int)b);
count++;
}

然后得到两个图像像素将rgb值解析回字节并反转你的分离过程,进行解码。