在Java中为图像设置DPI

时间:2014-07-14 12:17:10

标签: java image graphics2d

我想将文本字符串(五位数字)转换为DPI较低(因此尺寸较小)的图像。我在本网站上提到了其他一些帖子,但我从类似帖子中收集的以下代码对我不起作用。它运行正常,ans生成图像,但图像属性不符合代码中给出的DPI规范。

我不知道为什么Java在渲染图像时不识别这些规范,并且会欣赏任何想法/评论。有没有其他方法可以生成具有高DPI的图像或告诉Java使用什么像素大小? (我之后使用此图像进行Visual Crypto,因此希望在原始图像中具有低密度)。谢谢!

    String text = "12345";
    sFont font = new Font("TrueType", Font.TRUETYPE_FONT, 20);
    Iterator<ImageWriter> writers = ImageIO
            .getImageWritersByFormatName("jpg");
    ImageWriter writer = (ImageWriter) writers.next();

    ImageWriteParam param = writer.getDefaultWriteParam();

    ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
            .createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
    IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier,
            param);
    int DPI = 10;
    double dotsPerMilli = DPI / 10 / 2.54;

    IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
    IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
    horiz.setAttribute("value", Double.toString(dotsPerMilli));
    IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
    vert.setAttribute("value", Double.toString(dotsPerMilli));
    IIOMetadataNode dim = new IIOMetadataNode("Dimension");
    dim.appendChild(horiz);
    dim.appendChild(vert);
    root.appendChild(dim);
    metadata.mergeTree("javax_imageio_1.0", root);

    BufferedImage img = new BufferedImage(30, 14, BufferedImage.TYPE_INT_ARGB);

    writer.setOutput(ImageIO.createImageOutputStream("C:\\imagefromtext.jpg"));
    writer.write(metadata, new IIOImage(img, null, metadata), param);

    Graphics2D g2d = img.createGraphics();

    g2d.setFont(font);
    FontMetrics fm = g2d.getFontMetrics();
    g2d.dispose();
    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;

0 个答案:

没有答案