loading image into an imageView - java

i am a new android developer my first task with Intent is to pick an image from gallery and display it into an imageview so what i did is the following :
xml:
<Button
android:id="#+id/Intent_btn"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/button1"
android:text="Intent button"
android:onClick="openGallery" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignRight="#+id/Intent_btn"
android:layout_centerVertical="true" />
code:
ImageView imageview1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview1=(ImageView)findViewById(R.id.imageView1);
}
public void openGallery(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
imageview1.setImageBitmap(yourSelectedImage);
}
}
i managed to open the gallery and pick an image but it never load what would it be the problem ?

Add Permission to manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Here's some sample code on how to do that:
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
}
}

Add this permission :-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use this. This will work. Put this code in onActivityResult()
Uri selectedImage = data.getData();
String galleryImatePath = getRealPathFromURI(selectedImage);
InputStream stream = getContentResolver().openInputStream(selectedImage);
final Bitmap myImage = BitmapFactory.decodeStream(stream, null , bfOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.JPEG, 100, bos);
imageview1.setImageBitmap(myImage);
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

public void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
image.setImageBitmap(bitmap);
saveToInternalSorage(bitmap);
// save image to internal memory
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try as like this.

Related

Capturing the Image from camera intent image is rotating in some devices Android

I was trying to upload a profile of the user. In the app, users can choose from a gallery or camera.
While I was capturing the image from the camera, the image is rotating. I tried with exifinterface but the orientation getting as 0, and it works fine on some devices. How to solve this issue can anyone help me out?
xml
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/profile_image"
app:placeholderImage="#drawable/defaultprofile1"
app:placeholderImageScaleType="fitCenter"
app:roundingBorderColor="#color/browser_actions_bg_grey"
fresco:roundAsCircle="true"
android:layout_width="110dp"
android:layout_height="110dp"
android:scaleType="fitCenter" />
Code
draweeView3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View view){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ActivityCompat.requestPermissions(Objects.requireNonNull(getActivity()), new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
selectImage();
}
}
});
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Upload Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 0) {
if (data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
System.out.println("imagebitmap" + selectedImage);
Uri tempUri = getImageUri(Objects.requireNonNull(getContext()), selectedImage);
System.out.println("tempUri" + tempUri);
String picturePath = getRealPathFromURI(tempUri);
System.out.println("paaaaaaaa" + picturePath);
File f = new File(picturePath);
String imageName = f.getName();
System.out.println("file f" + f);
Uri imageUri = Uri.fromFile(new File(picturePath));// For files on device
draweeView3.setImageURI(imageUri);
}
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000, true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getActivity().getContentResolver() != null) {
Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
System.out.println("final path" + path);
cursor.close();
}
}
return path;
}

Android 10, select a photo from the gallery

people. I'm trying to get a photo from the Android 10 gallery. But, it tells me that bitmap = null, code below, what's wrong?
public void createIntent() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
if(Build.VERSION.SDK_INT < 29 ) {
this.bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} else {
this.bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.getContentResolver(), uri));
}
This is working on Android 10 also for me.
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String imagePath = getPath(data.getData());
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(imagePath),
null, options);
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, "Error loading the bitmap from the path: "
+ imagePath, e);
}
}
private String getPath(Uri uri) {
String path = "";
Cursor cursor = null;
try {
String[] projection = { MediaColumns.DATA };
cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor == null || !cursor.moveToFirst()) {
path = "";
} else {
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
path = cursor.getString(columnIndex);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return path;
}
I have created the solution.
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uri = data.getData();
InputStream stream = this.getContentResolver().openInputStream(uri);
bitmap = BitmapFactory.decodeStream(stream);
}
This code works for Build.VERSION.SDK_INT < 29 and for Build.VERSION.SDK_INT >= 29

i want to crop an image to set profile

I am new here and learning about android development. I want to crop image to set profile pic. when i used below codes its not done its jump to catch(something went wrong). kindly please help me solve this problem. used Image view on xml and got permission read and write on mainfest. And used ArthurHub/Android-Image-Cropper for cropping function
enter code here select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
premission();
if (pre == 2) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
Log.d("pp", "pp");
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{ super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && null != data)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
Uri selectedImage = data.getData();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
Uri selectedImage = result.getUri();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
profileimage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
Drawable myDrawable = profileimage.getDrawable();
profileimage.buildDrawingCache();
Bitmap bmap = profileimage.getDrawingCache();
BitmapDrawable bitmapDrawable = ((BitmapDrawable) myDrawable);
Bitmap bitmap1 = bitmapDrawable.getBitmap();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, stream);
imageInByte = stream.toByteArray();
encoded = Base64.encodeToString(imageInByte, Base64.DEFAULT);
} else
{
Toast.makeText(this, "You have not picked Image",
Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}

I compressed bitmap of image but it wouldn't go to the next activity

I am developing an android app. In this after taking a picture from gallery it will go to next page. but when I use small size of image,it works. But larger size is not working. I compressed bitmap. But still now problem exists.
Homepage.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
//int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//String picturePath = cursor.getString(columnIndex);
cursor.close();
}
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(imgDecodableString);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
// Set the Image in ImageView aimgView.setImageBitmap(bitmap);
Toast.makeText(this, "Picture loaded Successfully", Toast.LENGTH_LONG).show();
nextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myintent = new Intent(HomePage.this, Image_Recognition.class);
myintent.putExtra("picture", byteArray);
startActivity(myintent);
}
});
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
}
Picture.java
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
final Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
The logcat is "JavaBinder: !!! FAILED BINDER TRANSACTION !!!"
It's very necessary for my app. But I can't find any solution of this.

ImageView not showing image selected from gallery

So I have a button that loads the gallery, and selects an image using this code...
public void getGalleryImage(View v){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
But when it goes back to the original activity, the ImageView still doesn't show anything. It doesn't give me any errors, or anything like that. Here the XML for the ImageView...
<ImageView
android:id="#+id/galleryImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
How can I get it to show?
I ended up figuring something out. I just did...
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageURI(selectedImage);
}
This worked for what I was trying to accomplish.
Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri));
}
}
public class MainActivity extends AppCompatActivity{
ImageView image;
Button pick;
int TAG_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
pick = (Button) findViewById(R.id.button);
pick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,"Select Image "),TAG_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAG_IMAGE && resultCode == RESULT_OK )
{
Uri selectedImage = data.getData();
try
{
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String images = cursor.getString(columnIndex);
image.setImageURI(selectedImage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

Categories

Resources