'Why are images distorted after compressing image streams in PDF manually?

I am creating an application which converts Images to PDFs. It also has a feature which compresses the already created PDFs. Both features are working. But the problem occurs in case of compression, I.e. PDF file compressed successfully, but most of the images in compressed PDF file are distorted. I am Using Itext.pdf library for conversion. I am pasting both pictures, The first image is from the compressed PDF and the second one is from the Compressed PDF Image in normal PDF

Image in Compressed PDF

I am pasting my code also

// Code for the button, which user Presses to compress a PDF File, I just have chosen a static 
  file for testing here.

   btnCompressPdf.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              try {
                  File mfile;
                  mfile = getFilesDir();
                  farray = mfile.listFiles();
                  PdfReader reader = new PdfReader(new FileInputStream(farray[0]));
                  compressReader(reader);
                  saveReader(reader);
                  reader.close();
              }
              catch(FileNotFoundException ex){

              } catch (DocumentException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }

      });

Below is the code for functions which I have used in above Button code

private void compressReader(PdfReader reader) throws IOException {
    int n = reader.getXrefSize();
    PdfObject object;
    PRStream stream;

    for (int i = 0; i < n; i++) {

        object = reader.getPdfObject(i);
        if (object == null || !object.isStream())
            continue;
        stream = (PRStream) object;
        compressStream(stream);
    }

    // code of 'compressStream' function which is called in above function i-e compressReader

   private void compressStream(PRStream stream) throws IOException {
    PdfObject pdfSubType = stream.get(PdfName.SUBTYPE);
    System.out.println(stream.type());
    if (pdfSubType != null && pdfSubType.toString().equals(PdfName.IMAGE.toString())) {
        PdfImageObject image = new PdfImageObject(stream);
        byte[] imageBytes = image.getImageAsBytes();
        Bitmap bmp;

        bmp = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        if (bmp == null) return;

        int width = bmp.getWidth();
        int height = bmp.getHeight();

        Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        Canvas outCanvas = new Canvas(outBitmap);
        outCanvas.drawBitmap(bmp, 0f, 0f, null);

        ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();

        outBitmap.compress(Bitmap.CompressFormat.JPEG, 100, imgBytes);


        stream.clear();
        stream.setData(imgBytes.toByteArray(), false, PRStream.BEST_COMPRESSION);
        stream.put(PdfName.TYPE, PdfName.XOBJECT);
        stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
        stream.put(PdfName.FILTER, PdfName.DCTDECODE);
        stream.put(PdfName.WIDTH, new PdfNumber(width));
        stream.put(PdfName.HEIGHT, new PdfNumber(height));
        stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
        stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
    }
}
 
  // code for saveReader Function
    
  private void saveReader(PdfReader reader) throws DocumentException, IOException {
    Toast.makeText(MainActivity.this,"inside saveReader",Toast.LENGTH_LONG).show();
    FileOutputStream fileOutputStream = openFileOutput("myFileCompressed"+".pdf", 
    Context.MODE_PRIVATE);

    PdfStamper stamper = new PdfStamper(reader, fileOutputStream);
    stamper.setFullCompression();
    stamper.close();
    Toast.makeText(MainActivity.this,"Pdf Created Successfully",Toast.LENGTH_LONG).show();
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source