how to show image in image view - android

I am working on android custom camera application when i click on gallery view it show mobile default gallery and show photos that i clicked but i want when i click on gallery then clicked image show in my custom view how can i implement
public void clickedGallery(View view) {
if (MyDebug.LOG)
Log.d(TAG, "clickedGallery");
//Intent intent = new Intent(Intent.ACTION_VIEW, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Uri uri = null;
Media media = getLatestMedia();
if (media != null) {
uri = media.uri;
}
if (uri != null) {
// check uri exists
if (MyDebug.LOG)
Log.d(TAG, "found most recent uri: " + uri);
try {
ContentResolver cr = getContentResolver();
ParcelFileDescriptor pfd = cr.openFileDescriptor(uri, "r");
if (pfd == null) {
if (MyDebug.LOG)
Log.d(TAG, "uri no longer exists (1): " + uri);
uri = null;
}
pfd.close();
} catch (IOException e) {
if (MyDebug.LOG)
Log.d(TAG, "uri no longer exists (2): " + uri);
uri = null;
}
}
if (uri == null) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
if (!is_test) {
// don't do if testing, as unclear how to exit activity to finish test (for testGallery())
if (MyDebug.LOG)
Log.d(TAG, "launch uri:" + uri);
final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
try {
// REVIEW_ACTION means we can view video files without autoplaying
Intent intent = new Intent(REVIEW_ACTION, uri);
this.startActivity(intent);
} catch (ActivityNotFoundException e) {
if (MyDebug.LOG)
Log.d(TAG, "REVIEW_ACTION intent didn't work, try ACTION_VIEW");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// from http://stackoverflow.com/questions/11073832/no-activity-found-to-handle-intent - needed to fix crash if no gallery app installed
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("blah")); // test
if (intent.resolveActivity(getPackageManager()) != null) {
this.startActivity(intent);
} else {
preview.showToast(null, R.string.no_gallery_app);
}
}
}
}

Here is the complete code you can modify the requestCode to whatever you would have declared in your code and you can either pass the Uri or the actual location of the file in the next activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
if (requestCode == SELECT_FILE && (data != null)) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null,
null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
if(selectedImagePath == null) {
selectedImagePath = getActualPathFromUri(selectedImageUri);
}
cursor.close();
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
private String getActualPathFromUri(Uri selectedImageUri) {
Bitmap bitmap = null;
try {
bitmap = getBitmapFromUri(selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
if(bitmap == null) {
return null;
}
File imageFileFolder = new File(getCacheDir(),"appName");
if( !imageFileFolder.exists() ){
imageFileFolder.mkdir();
}
FileOutputStream out = null;
File imageFileName = new File(imageFileFolder, "appName-" + System.currentTimeMillis() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
Log.i("Exception", e.getMessage());
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageFileName.getAbsolutePath();
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
assert parcelFileDescriptor != null;
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}

When you back from camera after you take picture or back from gallery your onActivityResult method will call. So override your onActivityResult like the following
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
//Read your image here and set in your imageView
}
}
Edit:
Set image to image view
Inside of the onActivityResult
if(data.getData()==null){
bitmap = (Bitmap)data.getExtras().get("data");
}else{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
yourImageView.setImageBitmap(img);

Related

copy an image obtained by ACTION_GET_CONTENT to external storage

I would like to copy the image from the ACTION_GET_CONTENT and it should copy in Image directory in external storage.
I was getting the toast message but the image couldn't find in folder. Right now I giving permission manually so don't worry about that.
uriImagePath Gallary :content://com.android.providers.media.documents/document/image%3A3934
Destination: Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans"
I also added permission in the manifest file.
Here is my code. Any help much appreciated.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY = 22;
private static final String TAG = MainActivity.class.getSimpleName();
Button btn_copy;
private String imagepath = Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans/a.png";
private Uri uriImagePath;
private String realPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_copy = findViewById(R.id.btn_copy);
}
public void CopyImage(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
imagepath = Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans";
uriImagePath = Uri.fromFile(new File(imagepath));
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriImagePath);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent, REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY);
Toast.makeText(this, "Hi hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
realPath = ImageFilePath.getPath(MainActivity.this, data.getData());
// realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
Log.d("onActivityResult", "Destination imagePath :" + imagepath);
Log.d("onActivityResult", "uriImagePath Gallary :" + data.getData().toString());
Log.i(TAG, "onActivityResult: file path : " + realPath);
File f = new File(imagepath);
if (!f.exists())
{
try {
f.createNewFile();
copyFile(new File(getRealPathFromURI(data.getData())), f);
Log.i(TAG, "Inside if creating new file and call copy function: ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Video.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);
}
}

how to compress the bitmap image?

I want to upload image to the server. Converted my image as bitmap but still getting error. Bitmap too large to be uploaded into a texture
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
contentURI = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if (l == 0) {
imagePath = cursor.getString(columnIndex);
}
}
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), bitmap);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else if (requestCode == CAMERA) {
//if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
if (data != null) {
contentURI = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
if (l == 0) {
imagePath = cursor.getString(column_index_data);
}
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), thumbnail);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
saveImage(thumbnail);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
If i get picture using gallery means I am getting error as "Bitmap too large to be uploaded into a texture"
and if i get picture using camera means getting error as
"Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=18253, uid=10257 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()"
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress( Bitmap.CompressFormat.JPEG, 90, bytes );
wallpaperDirectory = new File( Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY );
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
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 "";
}
Try this, link to library
https://github.com/Tourenathan-G5organisation/SiliCompressor
/**
* Request Permission for writing to External Storage in 6.0 and up
*/
private void requestPermissions(int mediaType) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (mediaType == TYPE_IMAGE) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID);
}
} else {
if (mediaType == TYPE_IMAGE) {
// Want to compress an image
dispatchTakePictureIntent();
} else if (mediaType == TYPE_VIDEO) {
// Want to compress a video
dispatchTakeVideoIntent();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakeVideoIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
default:
}
}
private File createMediaFile(int type) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = (type == TYPE_IMAGE) ? "JPEG_" + timeStamp + "_" : "VID_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
type == TYPE_IMAGE ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_MOVIES);
File file = File.createTempFile(
fileName, /* prefix */
type == TYPE_IMAGE ? ".jpg" : ".mp4", /* suffix */
storageDir /* directory */
);
// Get the path of the file created
mCurrentPhotoPath = file.getAbsolutePath();
Log.d(LOG_TAG, "mCurrentPhotoPath: " + mCurrentPhotoPath);
return file;
}
private void dispatchTakePictureIntent() {
/*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");*/
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createMediaFile(TYPE_IMAGE);
} catch (IOException ex) {
// Error occurred while creating the File
Log.d(LOG_TAG, "Error occurred while creating the file");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// Get the content URI for the image file
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
photoFile);
Log.d(LOG_TAG, "Log1: " + String.valueOf(capturedUri));
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_CAMERA_PHOTO);
}
}
}
private void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
try {
takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
createMediaFile(TYPE_VIDEO));
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
Log.d(LOG_TAG, "VideoUri: " + capturedUri.toString());
startActivityForResult(takeVideoIntent, REQUEST_TAKE_VIDEO);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method which will process the captured image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//verify if the image was gotten successfully
if (requestCode == REQUEST_TAKE_CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
new ImageCompressionAsyncTask(this).execute(mCurrentPhotoPath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Silicompressor/images");
} else if (requestCode == REQUEST_TAKE_VIDEO && resultCode == RESULT_OK) {
if (data.getData() != null) {
//create destination directory
File f = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/Silicompressor/videos");
if (f.mkdirs() || f.isDirectory())
//compress and output new video specs
new VideoCompressAsyncTask(this).execute(mCurrentPhotoPath, f.getPath());
}
}
}
class ImageCompressionAsyncTask extends AsyncTask {
Context mContext;
public ImageCompressionAsyncTask(Context context) {
mContext = context;
}
#Override
protected String doInBackground(String... params) {
String filePath = SiliCompressor.with(mContext).compress(params[0], new File(params[1]));
return filePath;
/*
Bitmap compressBitMap = null;
try {
compressBitMap = SiliCompressor.with(mContext).getCompressBitmap(params[0], true);
return compressBitMap;
} catch (IOException e) {
e.printStackTrace();
}
return compressBitMap;
*/
}
#Override
protected void onPostExecute(String s) {
/*
if (null != s){
imageView.setImageBitmap(s);
int compressHieght = s.getHeight();
int compressWidth = s.getWidth();
float length = s.getByteCount() / 1024f; // Size in KB;
String text = String.format("Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", "ff", length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
}
*/
File imageFile = new File(s);
compressUri = Uri.fromFile(imageFile);
//FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName()+ FILE_PROVIDER_EXTENTION, imageFile);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), compressUri);
imageView.setImageBitmap(bitmap);
String name = imageFile.getName();
float length = imageFile.length() / 1024f; // Size in KB
int compressWidth = bitmap.getWidth();
int compressHieght = bitmap.getHeight();
String text = String.format(Locale.US, "Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", name, length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
As for loading large bimaps, read docs: https://developer.android.com/topic/performance/graphics/load-bitmap
Basically, you should provide inSampleSize to load load scaled version. Don't try to decode large bitmap without scaling, this will fail.

Pick image from Gallery - File not found when running newer Android versions

I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(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;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = (theCtx).getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'

Android: Saving image from gallery and then loading into imageview

I have an onclick that will allow a user to select a file from gallery like so:
case R.id.ColourCustom:
customBorderChange();
break;
private void customBorderChange() {
final ImageView QPBackground = (ImageView) findViewById(R.id.QPBackground);
menuHandler.removeCallbacks(menuTimer);
menuHandler.postDelayed(menuTimer, 5000);
bgHandler.removeCallbacks(runnableBG);
bgHandler.postDelayed(runnableBG, 2000);
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GALLERY_REQUEST);
File file = getFileStreamPath("QuickPlayBG.png");
if (file.exists()) {
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
} else {
String uri21 = "#drawable/bg_green";
int imageResource21 = getResources().getIdentifier(uri21, null, getPackageName());
QPBackground.setBackgroundResource(imageResource21);
}
}
This sends you here:
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
Uri selectedImageUri;
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null !=
data) {
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
cursor.close();
}
try {
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
saveBGFile(photo);
} catch (Exception e) {
String errorMessage = "Make your mind up mate!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
try {
saveQPConfig();
} catch (IOException e) {
String errorMessage = "Saving failed";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Which saves the file, using saveBGFile:
public void saveBGFile(Bitmap image) {
FileOutputStream out = null;
String filename = "QuickPlayBG.png";
try {
out = new FileOutputStream(filename);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue is with this line only:
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
It doesn't load anything. If I change "QuickPlayBG.png" to another filename that I am using in another part of my app, it loads fine. Both files are created using the same method. I verified that "QuickPlayBG.png" exists.
Compiler gives me the following hint:
E/﹕ ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
E/﹕ isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0
I think it has to do with the way I am saving the image, but I cannot see the fault myself. What could be the problem, that it is not loading the image?
Edit:
Here is the getThumbnail method I am using (works for another filename):
public Bitmap getThumbnail(String filename) {
final Context context = this;
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
Bitmap thumbnail = null;
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() !exist", ex.getMessage());
}
}
return thumbnail;
}
Use this short and sweet code for this. use intent of gallery.
1.declaire variable.
private static int RESULT_IMG = 1;
String imgString;
2.call intent of gallery on onclick of button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
3.onActivityResult to your code.
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
try {
if (requestCode == RESULT_IMG && responseCode == RESULT_OK
&& null != data) {
Uri pickedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgString = cursor.getString(columnIndex);
cursor.close();
//set bitmap to your imageview
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory.decodeFile(imgString));
} else {
Toast.makeText(this, "please select picture",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "error message", Toast.LENGTH_LONG)
.show();
}
}

Android camera capture activity returns null Uri

This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
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();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}

Categories

Resources