Make Uploaded Image Remain After Layout/activity Change
Solution 1:
Try these two methods:
First, show them a dialog to select option:
privatevoidselectImage() {
final CharSequence[] items = { getString(R.string.take_photo), getString(R.string.choose_from_gallery),
getString(R.string.cancel) };
AlertDialog.Builder builder = new AlertDialog.Builder(MyAccountActivity.this);
builder.setTitle(getString(R.string.upload_photo));
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
publicvoidonClick(DialogInterface dialog, int item) {
if (items[item].equals(getString(R.string.take_photo))) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} elseif (items[item].equals(getString(R.string.choose_from_gallery))) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, getString(R.string.select_file)),
SELECT_FILE);
} elseif (items[item].equals(getString(R.string.choose_from_gallery))) {
dialog.dismiss();
}
}
});
builder.show();
}
Receiving the actual image when a user has taken picture or selected from Gallery:
@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);
else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
}
Next is to handle cropping if you need - this is not necessary for this code to work but you can use it;
privatevoidonCaptureImageResult(Intent data) {
beginCrop(data.getData());
}
@SuppressWarnings("deprecation")privatevoidonSelectFromGalleryResult(Intent data) {
UriselectedImageUri= data.getData();
beginCrop(selectedImageUri);
}
privatevoidbeginCrop(Uri source) {
Uridestination= Uri.fromFile(newFile(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
privatevoidhandleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
try {
Bitmapbitmap= handleSamplingAndRotationBitmap(this, Crop.getOutput(result));
saveToInternalStorage(bitmap);
mUserProfilePhoto.setImageBitmap(readFromInternalStorage("profile.png"));
}catch (IOException e){ /* do nothing here */}
} elseif (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
Sometimes, you might want to rotate the image if it is not upright:
privatestatic Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)throws IOException {
intMAX_HEIGHT=1024;
intMAX_WIDTH=1024;
final BitmapFactory.Optionsoptions=newBitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStreamimageStream= context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmapimg= BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
privatestaticintcalculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of imagefinalintheight= options.outHeight;
finalintwidth= options.outWidth;
intinSampleSize=1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and widthfinalintheightRatio= Math.round((float) height / (float) reqHeight);
finalintwidthRatio= Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange// aspect ratio. For example, a panorama may have a much larger// width than height. In these cases the total pixels might still// end up being too large to fit comfortably in memory, so we should// be more aggressive with sample down the image (=larger inSampleSize).finalfloattotalPixels= width * height;
// Anything more than 2x the requested pixels we'll sample down furtherfinalfloattotalReqPixelsCap= reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
privatestatic Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage)throws IOException {
ExifInterfaceei=newExifInterface(selectedImage.getPath());
intorientation= ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
privatestatic Bitmap rotateImage(Bitmap img, int degree) {
Matrixmatrix=newMatrix();
matrix.postRotate(degree);
BitmaprotatedImg= Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
For storing as soon as the user picks from gallery or takes from Camera:
privatebooleansaveToInternalStorage(Bitmap image) {
try {
FileOutputStreamfos=this.openFileOutput("profile.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
returntrue;
} catch (Exception e) {
returnfalse;
}
}
Now for reading from storage:
private Bitmap readFromInternalStorage(String filename){
try {
FilefilePath=this.getFileStreamPath(filename);
FileInputStreamfi=newFileInputStream(filePath);
return BitmapFactory.decodeStream(fi);
} catch (Exception ex) { /* do nothing here */}
returnnull;
}
Inside onResume, I have this code to set the image to imageview:
@OverridepublicvoidonResume(){
super.onResume();
BitmapsavedProfilePhoto= readFromInternalStorage("profile.png");
if (savedProfilePhoto != null){
mUserProfilePhoto.setImageBitmap(savedProfilePhoto);
}
}
Almost done here:
Add this to your dependencies (build.gradle)
dependencies{
compile'com.soundcloud.android:android-crop:1.0.1@aar'
}
Finally, in your android manifest file, for cropping library to work, add this:
<activityandroid:name="com.soundcloud.android.crop.CropImageActivity"/>
That is all you need to enable selecting image from gallery or taking photo using your camera inside your app!
I hope this helps you and anyone else in need and good luck!
Post a Comment for "Make Uploaded Image Remain After Layout/activity Change"