Pages

Thursday, June 26, 2014

Capture image from camera in android


To capture image from android first fire an intent.
       
        private static final int REQUEST_CODE_IMAGE = 101;

        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CODE_IMAGE);


//  get data on on Activity Result use the below code

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
 if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {

   if (data != null) {
    if (data.getExtras().get("data") != null) {
 
     Uri fileUri = data.getData();
     String filePath = getRealPathFromURI(fileUri,
       MediaStore.Images.Media.DATA);
     File file = new File(filePath);
     String fileName = file.getName();


     try {
      Bitmap photo = (Bitmap) data.getExtras().get("data");
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      photo.compress(Bitmap.CompressFormat.PNG, 100, stream);



     } catch (Exception ex) {

     }
    }
   }
  }

Show or Read PDF in Android


To Show PDF file in your android phone first save it in your assets folder than read PDF file by using below two methods.
These methods first store your pdf in local storage than show it from local storage.

private void CopyReadAssets(String fileName) {
AssetManager assetManager = getAssets();

InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), fileName);
try {
in = assetManager.open(fileName);
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/" + fileName),
"application/pdf");

startActivity(intent);
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}