I want select photo by user from sd card and show in ImageView
My code :
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
e.printStackTrace();
}
imgOne.setImageBitmap(bm);
But this code not work
This code for onActivityResult after select photo by user
My class :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Log.i("error", "" + requestCode);
final ImageView imgOne = (ImageView) G.currentActivity.findViewById(R.id.imgOne);
if (requestCode == 1) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//bm.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
//bm = Bitmap.createScaledBitmap(bm, 600, 600, true);
}
catch (IOException e) {
e.printStackTrace();
}
imgOne.setImageBitmap(bm);
Log.i("error", "" + bm);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
When I upload the image from camera , Imageview appears white and it shows Bitmap too large to be uploaded into a texture (1968x4160, max=4096x4096) and I need to load the image whose zoom about 4096x4096 pixels high.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Bitmap originBitmap = null;
Uri selectedImage = data.getData();
InputStream imageStream;
Toast.makeText(getApplicationContext(), "Image successfully uploaded", Toast.LENGTH_SHORT).show();
try {
imageStream = getContentResolver().openInputStream(selectedImage);
originBitmap = BitmapFactory.decodeStream(imageStream);
originBitmap= originBitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (FileNotFoundException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
if (originBitmap != null) {
try {
originBitmap.setPixel(0, 0, getColor(R.color.white));
this.img.setImageBitmap(originBitmap);
Bitmap image = ((BitmapDrawable) img.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
}
catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I used below codes for taking image from camera and put it in Image View (imgViewAds).
private void BtnPhoto_Click(object sender, EventArgs e)
{
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.SetVmPolicy(builder.Build());
Intent cameraIntent = new Intent(Android.Provider.MediaStore.ActionImageCapture);
var activities = PackageManager.QueryIntentActivities(cameraIntent, 0);
if (activities.Count > 0)
{
addAds.ImageName = Guid.NewGuid().ToString() + ".jpg";
Java.IO.File imageFile = new Java.IO.File(AdsAdapter.ImagePath(addAds.ImageName));
Android.Net.Uri imageUri = Android.Net.Uri.FromFile(imageFile);
cameraIntent.PutExtra(MediaStore.ExtraSizeLimit, 1024*10);
cameraIntent.PutExtra(MediaStore.ExtraOutput, imageUri);
StartActivityForResult(cameraIntent, 0);
}
else
{
Toast.MakeText(this, "Not Camera", ToastLength.Long).Show();
}
}
And here is OnActivityResult the the camare send result here.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (resultCode == Result.Ok && (data != null))
{
Bundle extras = data.Extras;
Bitmap imageBitmap = (Bitmap)extras.Get("data");
imgViewAds.SetImageBitmap(imageBitmap);
MemoryStream stream = new MemoryStream();
imageBitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
addAds.AdsImage = stream.ToArray();
}
base.OnActivityResult(requestCode, resultCode, data);
}
but the data that sending to OnActivityResult is null and Image did not come to Image View.
When you pass EXTRA_OUTPUT with a URI to write to, the camera intent will be null and the picture is in the URI that you passed in.
so you could simply remove these two lines:
Android.Net.Uri imageUri = Android.Net.Uri.FromFile(imageFile);
cameraIntent.PutExtra(MediaStore.ExtraOutput, imageUri);
note that in this way you get the thumbnail of the image. so if you want the whole image you could use something like this (I haven't tested the code, but you could get the idea):
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
addAds.ImageName = Guid.NewGuid().ToString() + ".jpg";
Java.IO.File imageFile = new Java.IO.File(AdsAdapter.ImagePath(addAds.ImageName));
Uri uri = Uri.fromFile(file);
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmap = cropAndScale(bitmap, 300); // if you mind scaling
profileImageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am working on an demo application where I am taking picture then save it.
I want to display picture inside Image view . I don't understand why it is not working . I recently tried out some solution but non of them worked for me .
Is there anyone who can tell me what's wrong with my code .
// This is my code
private Button takePictureButton;
private ImageView imageView;
private Uri file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageview);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED&&grantResults[2]==PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
//Code that bind image with ImageView
if (resultCode == RESULT_OK) {
imageView.setMaxHeight(100);
imageView.setMaxWidth(100);
imageView.setImageURI(null);
imageView.setImageURI(file);
}
}
//Thanks in advance
I dont really understand what are you doing at here. But :
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
imageView.setMaxHeight(100);
imageView.setMaxWidth(100);
imageView.setImageURI(uri);
}
Replace this code on your activityResult, it is working for me.
Try this way it will work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
For more See this http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
In My case it worked for me:
private static Bitmap Image = null;
private static Bitmap rotateImage = null;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("resultCode", Integer.toString(resultCode));
Log.e("requestCode", Integer.toString(requestCode));
Log.e("Inside If","Success");
Uri mImageUri = data.getData();
try {
Image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
if (getOrientation(getApplicationContext(), mImageUri) != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
if (rotateImage != null)
rotateImage.recycle();
rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,true);
imageView.setImageBitmap(rotateImage);
//saveImagetoFolder(rotateImage);
} else {
imageView.setImageBitmap(Image);
// saveImagetoFolder(Image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I recognize text from the ABBYY business card it works. When I try it with a photo I took it failed. It does works on the demo from ABBYY so it's not my hardware.
Does anyone know why this is?
Code I use to take a photo:
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUESTCODE_PHOTO);
if(requestCode == REQUESTCODE_PHOTO){
if( resultCode == Activity.RESULT_OK){
RecognizerManager.recognizeText((Bitmap)data.getExtras().get("data"), this);
}
}
public static void recognizeText(final Bitmap bitmap, final RecognitionCallback listener){
RecognitionConfiguration config = new RecognitionConfiguration();
config.setRecognitionLanguages(Engine.getInstance().getLanguagesAvailableForOcr());
config.setRecognitionMode(RecognitionMode.FULL);
config.setImageProcessingOptions(RecognitionConfiguration.ImageProcessingOptions.FIND_ALL_TEXT);
RecognitionManager recManager = Engine.getInstance().getRecognitionManager(config);
try {
Object o = recManager.recognizeText(bitmap, listener);
Log.i("RESULT!", o.toString());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RecognitionFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I got it to work using this following code.
Photo taking in my RecognizeActivy:
final File photo = new File( Environment.getExternalStorageDirectory(), genPhotoFileName() );
RecognizeActivity.this.imageUri = Uri.fromFile( photo );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra( MediaStore.EXTRA_OUTPUT, imageUri );
startActivityForResult(intent, REQUESTCODE_PHOTO);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUESTCODE_PHOTO){
if( resultCode == Activity.RESULT_OK){
if(this.imageUri != null){
try{
final AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getContentResolver().openAssetFileDescriptor(this.imageUri, "r" );
long imageFileSize = assetFileDescriptor.getLength();
if( imageFileSize == AssetFileDescriptor.UNKNOWN_LENGTH ) {
throw new IOException( "UNKNOWN_LENGTH" );
}
InputStream is = assetFileDescriptor.createInputStream();
byte[] imageData = new byte[(int) imageFileSize];
is.read( imageData );
if(this.bitmap != null){
this.bitmap.recycle();
this.bitmap = null;
System.gc();
}
this.bitmap = BitmapFactory.decodeByteArray( imageData, 0, (int) imageFileSize, new Options() );
RecognizerManager.recognizeText(this.bitmap, this);
} catch(Exception e){
e.printStackTrace();
}
} else{
Log.e("ERROR", "img = null");
}
}
}
}
I'm recycling the bitmap because if I don't I get an OutOfMemory Exception after taking a few photo's.
Photo processing:
public static void recognizeText(final Bitmap bitmap, final RecognitionCallback progressListener){
final RecognitionConfiguration config = new RecognitionConfiguration();
config.setImageResolution(0);
config.setImageProcessingOptions( RecognitionConfiguration.ImageProcessingOptions.PROHIBIT_VERTICAL_CJK_TEXT);
for(RecognitionLanguage e : Engine.getInstance().getLanguagesAvailableForOcr()){
if(e.equals(RecognitionLanguage.English) || e.equals(RecognitionLanguage.Dutch)){
final Set<RecognitionLanguage> languages = EnumSet.noneOf( RecognitionLanguage.class );
languages.add(e);
config.setRecognitionLanguages(languages);
}
}
RecognitionManager recManager = Engine.getInstance().getRecognitionManager(config);
try {
Object o = recManager.recognizeText(bitmap, progressListener);
Log.i("RESULT!", o.toString());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RecognitionFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are implementing RecognitionCallback in the same activity you should implement it first, then call: recognizeText(this.bitmap, this) instead of RecognizerManager.recognizeText(this.bitmap, this); Also don`t forget to implement the 3 methods required: onPrebuiltWordsInfoReady, onRecognitionProgress, onRotationTypeDetected
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUESTCODE_PHOTO){
if( resultCode == Activity.RESULT_OK){
if(this.imageUri != null){
try{
final AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getContentResolver().openAssetFileDescriptor(this.imageUri, "r" );
long imageFileSize = assetFileDescriptor.getLength();
if( imageFileSize == AssetFileDescriptor.UNKNOWN_LENGTH ) {
throw new IOException( "UNKNOWN_LENGTH" );
}
InputStream is = assetFileDescriptor.createInputStream();
byte[] imageData = new byte[(int) imageFileSize];
is.read( imageData );
if(this.bitmap != null){
this.bitmap.recycle();
this.bitmap = null;
System.gc();
}
this.bitmap = BitmapFactory.decodeByteArray( imageData, 0, (int) imageFileSize, new Options() );
// CALL recognizeText(this.bitmap, this); instead of RecognizerManager.recognizeText(this.bitmap, this);
recognizeText(this.bitmap, this);
} catch(Exception e){
e.printStackTrace();
}
} else{
Log.e("ERROR", "img = null");
}
}
}
}
hi i am pretty new to android programming, this might be a simple problem for some but i am quite new to this. i want to open the gallery from one intent but want the picked image to be displayed on another intent i used the following code
public class GalActivity extends Activity {
Context ctx;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.result);
}
private static final int REQUEST_CODE = 1;
protected Bitmap bitmap;
private ImageView imageView=null;
/** Called when the activity is first created. */
// #Override
public void pickImage(View View) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
// ctx=this;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
the code works fine if the image is to be displayed on the same intent. but what should i do if it has to be displayed on another intent say "activity2".
As Bitmap implements Parcelable Interface, you can send it through intent directly, so do following in your onActivityResult Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(bitmap);
Intent intent= new Intent(this, SecondActivity.class);
intent.putExtra("BitmapImage", bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
and Read this Bitmap object in Another Activity by:
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");