繁体   English   中英

如何在不损失图像质量的情况下使用iText将图像转换为PDF?

[英]How to put image to PDF using iText without losing image quality?

我正在使用此代码:

Bitmap itemImage = reduceImageAtFilePathFromGallery(imageName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
itemImage.compress(Bitmap.CompressFormat.PNG, 100, stream);

imageAnswer = Image.getInstance(stream.toByteArray());

private Bitmap reduceImageAtFilePathFromGallery(String filePath) {
    // Decode image size 
    BitmapFactory.Options o = new BitmapFactory.Options(); 
    o.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(filePath, o); 

    // The new size we want to scale to 
    final int REQUIRED_SIZE = 256; 

    // Find the correct scale value. It should be the power of 2. 
    int width_tmp = o.outWidth, height_tmp = o.outHeight; 
    int scale = 1; 
    while (true) { 
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) 
            break; 
        width_tmp /= 2; 
        height_tmp /= 2; 
        scale *= 2; 
    } 

    // Decode with inSampleSize 
    BitmapFactory.Options o2 = new BitmapFactory.Options(); 
    o2.inSampleSize = scale; 
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2); 
    return bitmap;
}

但是图像质量变差。 然后,我还尝试了以下代码:

Image imageAnswer = getAndResizeImage(imageName);

private Image getAndResizeImage(String imageFilename){
    final File imageFile = new File(imageFilename);
    if (imageFile.exists()) {
        Bitmap b = null;
        try {
            File f = new File(imageFilename);
            b = BitmapFactory.decodeFile(f.getAbsolutePath());

            //calculate how many bytes our image consists of.
            int bytes = getSizeInBytes(b);

            ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
            b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

            byte[] array = buffer.array(); //Get the underlying array containing the data.
            Image image = Image.getInstance(array);

            return image;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
    }

    return null;
}

它给出了这个错误:

09-09 15:08:58.368:W / S

ystem.err(1385):java.io.IOException:字节数组不是可识别的图像格式。 09-09 15:08:58.378:W / System.err(1385):at com.itextpdf.text.Image.getInstance(Image.java:442)09-09

在这行代码上:

Image image = Image.getInstance(array);

有什么办法可以使用iText在PDF上获得高质量的图像?

使用JPEG压缩格式而不是PNG

itemImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM