0

EDIT First of all, I am new with Android and don't have much grip when it comes to gallery functionality and manipulating its method so please have a little patience and guide me of what I am doing wrong.

Scenario I am setting my app photos inside a grid view (kind of file explorer). When I browse and open some image by clicking some folder in gridview using intent (note that this is not Intent.ACTION_PICK), just moving from one activity to another and passing the path of clicked item in putString() method. Till this point, it works fine but the problem is that I don't know how to retrieve the information about the Uri, Bitmap etc.

Can you please guide me what strategy I have to use in this scenario. I have seen many question for the past 2 days here at SO, but most of them are using gallery Action Pick intent, and getting results in onActivityResult() and using getData() method to retrieve information about the picked image. I also managed to perform it successfully when I opened the camera and used onActivityResult() method to retrieve the info but this is different scenario ( atleast for me as a beginner ) Please guide me the right way of how to figure it out. All I have is the path of that particular image opened in new activity.

Below is the activity code, I used to open an image from my Gridview activity.

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.scanlibrary.ScanConstants;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import static com.itextpdf.text.Image.getInstance;

/**
 * Created by ADMIN on 6/23/2016.
 */
public class ImageOpenedActivity extends Activity {
    ImageView imageView;
    String received;
    private Button pdfConverter, openPDFConverter;
    String path;
    String outputPath;
    File openfile;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if (extras == null) {
                received = null;
            }
            else {
                received = extras.getString("Image");

            }
        }
        else {
            received = (String) savedInstanceState.getSerializable("Image");

        }
        setContentView(R.layout.imageopened);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system

        pdfConverter = (Button) findViewById(R.id.PDF);
        openPDFConverter = (Button) findViewById(R.id.openPDF);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setImageURI(Uri.parse(received));
        outputPath = ScanConstants.IMAGE_PATH + File.separator + "PDF" + dateTime + ".pdf";
        Bitmap viewBitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);//i is imageview whch u want to convert in bitmap
        Canvas canvas = new Canvas(viewBitmap);
        imageView.draw(canvas);
        Uri tempUri = getImageUri(getApplicationContext(), viewBitmap);

        // CALL THIS METHOD TO GET THE ACTUAL PATH
        File finalFile = new File(getRealPathFromURI(tempUri));
        path = String.valueOf(finalFile);


//openPDFConverter.setOnClickListener(new View.OnClickListener() {
//@Override
//public void onClick(View v) {
//        openfile = new File(outputPath);
//        Intent target = new Intent(Intent.ACTION_VIEW);
//        target.setDataAndType(Uri.fromFile(openfile), "application/pdf");
//        target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
//
//        Intent intent = Intent.createChooser(target, "Open File");
//        try {
//        startActivity(intent);
//        } catch (ActivityNotFoundException e) {
//        Log.e("Errorrrr ::::", outputPath);
//        }
//        }
//        });
//        // PDF Converter onclick method
//        pdfConverter.setOnClickListener(new View.OnClickListener() {
//@Override
//public void onClick(View view) {
//        // Will run the conversion in another thread to avoid the UI to be frozen
//        Thread t = new Thread() {
//public void run() {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
//
//        // Input file
//        //inputPath = Environment.getExternalStorageDirectory() + File.separator + "test" + dateTime + ".jpg";
//
//        // Output file
//        //   outputPath = Environment.getExternalStorageDirectory() + File.separator + "PDF"+dateTime+".pdf";
//        outputPath = ScanConstants.IMAGE_PATH + File.separator + "PDF" + dateTime + ".pdf";
//
//        Log.e("Passed path is:::", path);
//// Run conversion
//final boolean result = ImageOpenedActivity.this.convertToPdf(path, outputPath);
//
//        // Notify the UI
//        runOnUiThread(new Runnable() {
//public void run() {
//        if (result) {
//        openPDFConverter.setVisibility(Button.VISIBLE);
//        Toast.makeText(ImageOpenedActivity.this, "The JPG was successfully converted to PDF.", Toast.LENGTH_SHORT).show();
//        }
//        else
//        Toast.makeText(ImageOpenedActivity.this, "An error occured while converting the JPG to PDF.", Toast.LENGTH_SHORT).show();
//        }
//        });
//        }
//        };
//        t.start();
//        }
//        });

    }


    public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        Log.e("Bitmap received ::::", String.valueOf(inImage));
        //inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        Log.e("getImageURI path:", String.valueOf(path));

        return Uri.parse(path);
    }


    public String getRealPathFromURI(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        Log.e("getRealPathFromURI:::", String.valueOf(uri));
        Log.e("URI received", String.valueOf(uri));
        return cursor.getString(idx);
    }

    public boolean convertToPdf(String jpgFilePath, String outputPdfPath) {
        try {
            // Check if Jpg file exists or not
            File inputFile = new File(jpgFilePath);
            if (!inputFile.exists()) {
                Log.e("Input File::", String.valueOf(inputFile));
                throw new Exception("File '" + jpgFilePath + "' doesn't exist.");
            }

            // Create output file if needed
            File outputFile = new File(outputPdfPath);
            if (!outputFile.exists()) {
                outputFile.createNewFile();
                Log.e("Output File::", String.valueOf(outputFile));

            }

            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(outputFile));
            document.open();

            com.itextpdf.text.Image image = getInstance(jpgFilePath);
            image.setAbsolutePosition(0, 0);
            image.scaleAbsolute((float) 2549 * (float) .24, (float) 3304 * (float) .24);
            image.scaleToFit((float) 2549 * (float) .24, (float) 3304 * (float) .24);
            document.add(image);
            Log.e("After document added::", String.valueOf(image));

            document.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }   
    }
Umair
  • 438
  • 1
  • 8
  • 19
  • I've added the iTextG tag, assuming that you are using the official Android port of iText. Your question contains a lot of code, but you don't tell us what the problem is. You just say "it works for some images, but not for all". That is insufficient information to answer the question. Your question is not [on topic](http://stackoverflow.com/help/on-topic) because *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself* (copy/paste from the FAQ on SO) – Bruno Lowagie Jun 26 '16 at 07:37
  • Also: you are doing really weird things in your code. `setDpi()` should not be used and you are defining the image dimensions in three different ways! That's absurd, please choose either `scalePercent()`, or `scaleAbsolute()`, or `scaleToFit()`. Don't use all three of those methods! – Bruno Lowagie Jun 26 '16 at 07:40
  • Finally: you are importing JPEGs into a PDF using iTextG. JPEG is the easiest image format to import because all the bytes can be copied into the PDF file literally. iText doesn't change a single byte of the original JPEG. If all of the images in the PDF are black, you should examine the PDF using [iText RUPS](http://itextpdf.com/Products/itext-rups). Maybe the images are stored inside the PDF correctly but using the wrong scale. – Bruno Lowagie Jun 26 '16 at 07:43
  • Figured it out, no need to find uri's and bitmap if I know the exact path of image. Just passed it to the pdf converter method, and thats it ! – Umair Jun 26 '16 at 14:07

0 Answers0