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".
Related
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.
Having some trouble figuring out how to set the imageview to the picture I just captured with the camera. Would be a bonus if there was some way to display multiple captured pictures at once. Whenever I click the button, a previous image captured appears, then the camera opens, which isn't right. Id like the imageview to be blank, I click the button, take a picture, then that picture is displayed in the imageview. I believe that this line is out of place, but i'm unsure as to how/ where to move it. mimageView.setImageURI(outputFileUri);
public class cameraclass extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
final ImageView mimageView;
mimageView = (ImageView) this.findViewById(R.id.image_from_camera);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.take_image_from_camera);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Here, the counter will be incremented each time, and the
// picture taken by camera will be stored as 1.jpg,2.jpg
// and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
}
catch (IOException e)
{
}
//Uri outputFileUri = Uri.fromFile(newfile);
Uri outputFileUri = FileProvider.getUriForFile(getApplicationContext() , "com.example.android.com220finalapp.provider", newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
mimageView.setImageURI(outputFileUri);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
I believe that this line is out of place, but i'm unsure as to how/ where to move it.
startActivityForResult() is asynchronous. Your photo will not have been taken by the time that method returns. You need to load the image into the ImageView in onActivityResult(), if you got a RESULT_OK response.
However, while setImageURI() may work, it has never been an especially good idea, as it will freeze your app for a while as it loads the photo. There are many image loading libraries for Android that will handle loading your ImageView asynchronously.
I'm creating a simple app to take a picture. this is my code
Button b1;
ImageView iv;
String TAG = "MAIN ACTIVITY";
File photo;
private Uri mImageUri;
private File createTemporaryFile(String part, String ext) throws Exception {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File tempDir = new File(externalStorageDirectory + "/cameratest/");
if (!tempDir.exists()) {
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
// place where to store camera taken picture
photo = createTemporaryFile("picture", ".jpg");
photo.delete();
} catch (Exception e) {
Log.v(TAG, "Can't create file to take picture!");
Toast.makeText(getApplicationContext(), "Please check SD card! Image shot is impossible!",
Toast.LENGTH_SHORT).show();
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, 0);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG, mImageUri.toString());
Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.toString());
iv.setImageBitmap(bitmap);
}
}
as you can see i've added eLog.d(TAG, mImageUri.toString()); at the end and in the logcat (as well as the FileNotFoundException) i see this direcory:
03-27 00:43:30.498 30526-30526/myapplication.example.falcoleo.cameratest1 D/MAINÂ ACTIVITY: file:///storage/emulated/0/cameratest/picture459838058.jpg
03-27 00:43:30.499 30526-30526/myapplication.example.falcoleo.cameratest1 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/cameratest/picture459838058.jpg: open failed: ENOENT (No such file or directory)
guess if this directory exists?
spoler alert, it does. And it's not like the image is created after the BitmapFactory.decodeFile. I really do not understand what i'm doing wrong. Everything works fine except when it actually has to display the photo, then it just does not display it. just blank. Like WTF m8 i'm just trying to do my job no need to go crazy, you know.
Replace mImageUri.toString() with mImageUri.getPath().
decodeFile expects a path, not an uri string.
file:///storage/emulated/0/cameratest/picture459838058.jpg
Remove file:// because the decodeFile() expects a file system path.
/storage/emulated/0/cameratest/picture459838058.jpg
Use BitmapFactory.decodeStream instead of BitmapFactory.decodeFile.
try ( InputStream is = new URL( file_url ).openStream() ) {
Bitmap bitmap = BitmapFactory.decodeStream( is );
}
Source https://stackoverflow.com/a/28395036/5714364
Ok for me it was the file path was wrong so I needed to get the real filepath.
First
File file = new File(getPath(uri));
public String getPath (Uri uri)
{
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,
projection,
null,
null,
null);
if (cursor == null)
return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
Then Back To Uri
Uri newUri = Uri.fromFile(file);
This conversion to file and back to uri did the trick for me. I was receiving simple data from action.SEND.
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
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.