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();
}
}
Related
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 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.
I am having trouble converting from an image uri to a bitmap to then show it in an image view, yet I am getting an unhandled exception when converting into a bitmap.
Here is the code:
public class MainActivity extends AppCompatActivity {
public static final int PICK_IMAGE = 1;
Image picture = new Image();
Context context = getApplicationContext();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGallery = (Button) findViewById(R.id.btnGallery);
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
Uri imageUri = intent.getData();
Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
}});
You are not picking the image on right way. Remove these three lines of code from you onClick method you will move them inside onActivityResult:
Uri imageUri = intent.getData();
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
Then in your (probably) Activity override onActivityResult and do inside something like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
try {
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please try this code, this is working for my app.
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
// path = saveImage(bitmap);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(thumbnail);
path = saveImage(thumbnail);
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
I am writing a contact form in which I am creating a file picker with a button, but the problem is that if file size is large, its unfortunately stops and if there is no file explorer than its giving null pointer exception.
Here is the code of intent
Intent intent= new Intent(Intent.ACTION_PICK);
intent.setAction(Intent.ACTION_GET_CONTENT);// its optional
intent.setType("image/*");
final int SELECT_IMAGE = 1;
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_IMAGE);
and here is the code of on activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 1 && resultCode == RESULT_OK ) {
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();
//this code converts image in base64 and the string is to be sent along post method:
yourSelectedImage = BitmapFactory.decodeFile(filePath);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, resultCode, Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
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.