Saving URI image or converting to bitmap while maintaining resolution - java

So I've got my image to successfully pass to a URI...however I don't know how to save it or convert it to a bitmap while still maintaining resolution. Any suggestions? Thank you.
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CALL THE PICTURE (this works)
File t = new File (STORAGE_PATH + "savedAndroid.jpg");
mURI = Uri.fromFile(t);
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mURI);
startActivityForResult(i,0); //0 is default camera
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
imageView.setImageURI(mURI); //this seems to work...by itself
//save the image or convert it to a bitmap to use with tesseract...
}

InputStream is = context.getContentResolver().openInputStream(mURI);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, new BitmapFactory.Options());
Then use it however you want.
Hope this helps.

Related

Why does the Camera Intent not returning the image to the ImageView?

What I am trying to achieve is on the map long press it brings up and custom dialog view with 3 buttons, one for photo, one for save and one for cancel.
So at the moment when tapping on photo the camera intent opens and I can take a photo. Upon clicking "ok" the intent returns to the custom dialog window but no image is displayed?
This is my code I am using at the moment:
public void onMapLongClick(LatLng point) {
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View deleteDialogView = factory.inflate(R.layout.custom_dialog, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(MainActivity.this).create();
deleteDialog.setView(deleteDialogView);
deleteDialogView.findViewById(R.id.btn_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String f = System.currentTimeMillis()+".jpg"; // Designated name
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), f);
fileUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch (requestCode) {
case TAKE_PICTURE:
ImageView imgView = findViewById(R.id.a);
imgView.setImageURI(fileUri);
break;
}
}
});
Notice that you pass 'fileUri' to the intent, so you also need to get it from the returned intent.
Try replacing imgView.setImageURI(fileUri);
with imgView.setImageURI(data.getData());
or
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
which will give you the URI with the image.

How to transfer image to another activity

I have two activity, First with button, which calls void openCamera, and second, where I need to get bitmap.
I have two questions:
1. Which line of code is saving pictures?
2. How I can take a bitmap from OnActivityResult and get it in another activity?
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "Taking pic from the Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SelectedImage.setImageURI(image_uri);
try {
Bitmap ImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), image_uri);
detectImage(ImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Don't think about passing it through Bundle (docs: https://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject)
I think, you should save the image in internal storage of your app and then load it in your second activity.
Here are the answers explaining how to do that: Saving and Reading Bitmaps/Images from Internal memory in Android
Pass image uri as string along with activity intent
mIntent.putExtra("image", image_url.toString());
In the receiving activity get the uri and move your code to generate bitmap there.
String image_url = getIntent().getStringExtra("image");
//your code to get bitmap

How to take gallery image as input stream

I am trying to read image from gallery and then use that image for input straming , below is my code
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGetImageButton = (Button) findViewById(R.id.button_getImage);
mGetImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// SET action AND miniType
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
// REQUEST Uri of image
startActivityForResult(intent, REQUEST_IMAGE);
}
});
mImageViewForGallery = (ImageView) findViewById(R.id.imageView2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {return;}
if (requestCode == REQUEST_IMAGE) {
Uri uri = data.getData();
// SET image
mImageViewForGallery.setImageURI(uri);
Drawable drawable = mImageViewForGallery.getDrawable();
InputStream is;
is = this.getResources().openRawResource(R.drawable.img1);
Bitmap bmInImg = BitmapFactory.decodeStream(is);
}
}
In above code is = this.getResources().openRawResource(R.drawable.img1); is reading image from drawable folder name img1 , but now my image is the image I select from gallery , How I can take that image as input stream, as I tried it like
InputStream is;
is=uri;
But its showing error , well am new to java from c++.
Edit, after #Shawn answer I put this code in onActivityResult function after line Drawable drawable = mImageViewForGallery.getDrawable(); :
InputStream is = this.getContentResolver().openInputStream(uri);
Bitmap bmInImg = BitmapFactory.decodeStream(is);
InputStream Vign = this.getResources().openRawResource(R.drawable.p);
Bitmap bmInImg2 = BitmapFactory.decodeStream(Vign);
mPhotoIntArray = new int[bmInImg.getWidth() * bmInImg.getHeight()];
nPhotoIntArray = new int[bmInImg.getWidth() * bmInImg.getHeight()];
vPhotoIntArray = new int[bmInImg2.getWidth() * bmInImg2.getHeight()];
But its showing me below error on this.getContentResolver().openInputStream(uri);
Error :
Unhandled exception type FileNotFoundException
Error come when I use InputStream Vign = this.getResources().openRawResource(R.drawable.p); in the code.
if you have the Uri to the image, you resolve it with content resolver:
InputStream is = context.getContentResolver().openInputStream(uri);
Don't forget to close the stream. (and check for null). context sometime is your activity or "this".

I want to open the android camera without saving the picture to gallery

I want the picture to go straight to the ImageView without saving it to gallery if possible. As shown in the screenshot, it will ask to save everytime and will save straight to the gallery. Can this be achieved, or will I have to make my own ImageView camera?
public class Main extends Activity {
ImageView ivPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPhoto = (ImageView) findViewById(R.id.ivPic);
}
public void TakePhoto(View v){
Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent,0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==0){
Bitmap camImage = (Bitmap) data.getExtras().get("data");
ivPhoto.setImageBitmap(camImage);
}
}
Finally got what I wanted. Thanks guys
public class Main extends Activity {
ImageView ivPhoto;
File myFilesDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPhoto = (ImageView) findViewById(R.id.ivPic);
myFilesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.example.project/files");
System.out.println (myFilesDir);
myFilesDir.mkdirs();
}
public void TakePhoto(View v){
Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
camIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(myFilesDir.toString()+"/temp.jpg")));
startActivityForResult(camIntent, 0);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==0){
try {
Bitmap cameraBitmap;
cameraBitmap = BitmapFactory.decodeFile(myFilesDir + "/temp.jpg");
Bitmap.createBitmap(cameraBitmap);
ivPhoto.setImageBitmap(cameraBitmap);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
From my understanding you don't want this to be showing up by any media scanner, like the gallery application. What you should actually do is not store it in a root directory like pictures or sdcard, but store it in your applications data folder in the sdcard in Android/data/package/.
You can get this using: http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
File myFilesDir = getExternalFilesDir(null);
OR
File myFilesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Note that it will only work on API versions 8 or above.
If you don't want to use the function you can simply just use:
File myFilesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files");
myFilesDir.mkdirs();
Use my Code. I am taking a picture using camera intent and before saving it to gallery , it is showed to the user with a Save and Cancel Button :-
Call Camera Intent :-
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator +CommonFunction.getDateTime()+".jpg"; // Get File Path
Intent takePictureFromCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureFromCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
startActivityForResult(takePictureFromCameraIntent, 123);
onActivityResult : -
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT)
{
if (resultCode == Activity.RESULT_OK)
{
String galleryImatePath = SD_CARD_TEMP_DIR; // make SD_CARD_TEMP_DIR Global so that you can access it here from camera intent or pass it in put Extra method and retrieve it here
File f = new File(galleryImatePath);
try {
Bitmap cameraBitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
bmOptions.inBitmap = cameraBitmap;
bmOptions.inMutable = true;
cameraBitmap = BitmapFactory.decodeFile(galleryImatePath,bmOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
//To Rotate image Code
ExifInterface exif = new ExifInterface(galleryImatePath);
float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
System.out.println(rotation);
float rotationInDegrees = exifToDegrees(rotation);
System.out.println(rotationInDegrees);
Matrix matrix = new Matrix();
matrix.postRotate(rotationInDegrees);
final Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
FileOutputStream fos=new FileOutputStream(galleryImatePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.write(bos.toByteArray());
cameraBitmap.recycle();
System.gc();
fos.flush();
fos.close();
// To set image in imageview in dialog
Capdialog = new Dialog(AddToDo.this,android.R.style.Theme_NoTitleBar_Fullscreen);
Capdialog.setContentView(R.layout.captiondialog);
Capdialog.setCancelable(false);
TextView cancel = (TextView) Capdialog
.findViewById(R.id.cancel);
TextView done = (TextView) Capdialog.findViewById(R.id.done);
Capdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ImageView img = (ImageView) Capdialog.findViewById(R.id.image);
img.setImageBitmap(rotatedBitmap);
}
catch(Exception e){}
}
}
}
implement your done and cancel on click listener - what you want to do in them.
My code will capture your image, rotate it in the right direction irrespective of camera rotation and show it to you in a dialog before saving it
Google provided a tutorial on this exact topic: Controlling the Camera

Android camera to take multiple photos [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The problem class:
public class problem extends Activity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
iv=(ImageView) findViewById(R.id.imageView1);
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm=(Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bm);
}
}
This is what I wanted to do:
Take multiple photos
show them in the screen
store them in the mysql databse.
I am new to android please tell me how to do that.I searched.But I could not find a answer.
From this code IT TAKE ONLY ONE PHOTO.
Show Image on Screen Before Saving :
Use my Code. I am taking a picture using camera intent and before saving it to gallery , it is showed to the user with a Save and Cancel Button :- Call Camera Intent :-
// This code is to call the camera intent. Basically it will start your camera. Put this code in a button or something
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator +CommonFunction.getDateTime()+".jpg"; // Get File Path
Intent takePictureFromCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureFromCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
startActivityForResult(takePictureFromCameraIntent, 123);
onActivityResult : -
// This function is called when you come back to your activity after the intent has finished. Do read android documentation on Google. It will Help
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT)
{
if (resultCode == Activity.RESULT_OK)
{
String galleryImatePath = SD_CARD_TEMP_DIR; // make SD_CARD_TEMP_DIR Global so that you can access it here from camera intent or pass it in put Extra method and retrieve it here
File f = new File(galleryImatePath);
try {//This code will rotate your image if you have taken the image by rotating the camera
Bitmap cameraBitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
bmOptions.inBitmap = cameraBitmap;
bmOptions.inMutable = true;
cameraBitmap = BitmapFactory.decodeFile(galleryImatePath,bmOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
//To Rotate image Code
ExifInterface exif = new ExifInterface(galleryImatePath);
float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
System.out.println(rotation);
float rotationInDegrees = exifToDegrees(rotation);
System.out.println(rotationInDegrees);
Matrix matrix = new Matrix();
matrix.postRotate(rotationInDegrees);
final Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
FileOutputStream fos=new FileOutputStream(galleryImatePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.write(bos.toByteArray());
cameraBitmap.recycle();
System.gc();
fos.flush();
fos.close();
// To set image in imageview in dialog. This code will set your image in a custon dialog box "captiondialog". It will contain a full width and height imageview and two textviews - done and cancel. It is upto u what you want to define in the textview's click listener. For example, you can pass the storing image in database in the "Done" textview and "Cancel" textview will dismiss your captiondialog and you app will return to your activity
Capdialog = new Dialog(AddToDo.this,android.R.style.Theme_NoTitleBar_Fullscreen);
Capdialog.setContentView(R.layout.captiondialog);
Capdialog.setCancelable(false);
TextView cancel = (TextView) Capdialog
.findViewById(R.id.cancel);
TextView done = (TextView) Capdialog.findViewById(R.id.done);
Capdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ImageView img = (ImageView) Capdialog.findViewById(R.id.image);
img.setImageBitmap(rotatedBitmap);
}
catch(Exception e){}
}
}
}
implement your done and cancel on click listener - what you want to do in them. My code will capture your image, rotate it in the right direction irrespective of camera rotation and show it to you in a dialog before saving it
This code will store your image in DB.You have to use "blob" to store image.. Use This Code :-
public void insertImageInDb(int id , Bitmap img ) {
byte[] data = bos.toByteArray(); // Use This or the code in comments below
/* ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
byte[] data = outputStream.toByteArray();*/
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
There's an alternative intent action for the device camera that launches the camera in still image mode and does not exit until the user is finished with the activity:
Intent intent = new Intent(
MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
this.startActivity(intent);
Used with a ContentObserver this was exactly what I needed to accomplish. or Handle this in ActivityResult.
Note :- if you are new to android, this is too hard for you to understand now. Please read the android documentation first on google and read tutorials. Make basic apps. Learn first

Categories

Resources