I am trying to copy image using below code:
Intent intentImage = new Intent();
intentImage.setType("image/*");
intentImage.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intentImage, 10);
With this i am able to open all image content.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10) {
if (resultCode != RESULT_OK) return;
Uri selectedImageUri = data.getData();
try {
String selectedImagePath1 = getPath(selectedImageUri);
File file = new File(selectedImagePath1);
String fna = file.getName();
String pna = file.getParent();
File fileImage = new File(pna, fna);
copyFileImage(fileImage, data.getData());
} catch (Exception e) {
}
}
}
private void copyFileImage(File src, Uri destUri) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now i am successfully get path and name of the image .
Now when i run the above code then it gives me error of requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission().
so i have put the permission in manifest :
i have also defined the permission for read and write internal/external storage.
But still i am getting this error.
How can i copy image ?
Select picture using below code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);
this will open gallery, after selecting pic you will get selected pic uri in below code
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK)
{
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
File sel = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
imageView1.setImageBitmap(bitmap);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, 600,370, true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);
String StrBase64 = Base64.encodeToString(blob.toByteArray(), Base64.DEFAULT);
imageView1.setImageBitmap(resized);
// Toast.makeText(getApplicationContext(), ""+selectedImagePath, Toast.LENGTH_LONG).show();
}
break;
}
}
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
add permission in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
this way you will get selected image in Base64 to string
Try this code-
Image will copy in SaveImage folder in sd card
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK)
{
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
File sel = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
imageView1.setImageBitmap(bitmap);
SaveImage(bitmap);
}
break;
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/SaveImage");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
My app work perfectly when select image from Pictures or images categories in Gallery but app getting crash when select image from recent images
This is my intent call
galleryLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (EasyPermissions.hasPermissions(getActivity(), perms_gallery)) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
}else {
EasyPermissions.requestPermissions(getActivity(), getString(R.string.read_file),
READ_REQUEST_CODE, perms_gallery);
}
}
});
Crash happen from here String id = wholeID.split(":")[1];
public String getPathFromUriGallery(Context context, Uri uri) {
Cursor cursor = null;
try {
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
String[] filePath = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePath, sel, new String[]{id}, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
return cursor.getString(columnIndex);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
this my error log
Process: io.test.susitkMed.doctor, PID: 9576
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=3;doc=encoded=0ajgvv25pDn5wcNiiiv1YFYu7neaIdrulcWk/kBdEa8TqupNEKLhnLzz flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } }} to activity {io.test.susitkMed.doctor/io.test.susitkMed.doctor.ui.activities.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at android.app.ActivityThread.deliverResults(ActivityThread.java:4520)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
I found this solution from this github sample https://github.com/maayyaannkk/ImagePicker
This is the solution for above issue
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String imageEncoded = getRealPathFromURI(getActivity(), selectedImageUri);
Bitmap selectedImage = BitmapFactory.decodeFile(imageString);
image.setImageBitmap(selectedImage);
}
}
These method use for get image url
public String getRealPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = new File(getFilename(context));
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
private String getFilename(Context context) {
File mediaStorageDir = new File(context.getExternalFilesDir(""), "patient_data");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
return mediaStorageDir.getAbsolutePath() + "/" + mImageName;
}
Use this methods instead..
public String getImagePathFromUri(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Use Document provider instead.
For eg:
Intent it = new Intent();
it.setAction(Intent.ACTION_GET_CONTENT);
it.setType("image/*");
startActivityForResult(it, 1000);
----------------------
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK && data != null) {
try {
Bitmap bm = getBitmapFromUri(data.getData());
iv.setImageBitmap(bm);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
When I select the image from recent then the image is broken in android | Multiple images from recent
I have mentioned below my answer link please go there and find your solutions
You can find the full post from this link || Click link here
Also, you can find here
Sample preview
Call multiple images select
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
*gallery*.launch(i);
gallery basically startActivityForResult(i,123) and OnActivityResult method is deprecated, the gallery is alternative which is defined below
ActivityResultLauncher<Intent> gallery = choosePhotoFromGallery();
and choosePhotoFromGallery() is method which is define below
private ActivityResultLauncher<Intent> choosePhotoFromGallery() {
return registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
try {
if (result.getResultCode() == RESULT_OK) {
if (null != result.getData()) {
if (result.getData().getClipData() != null) {
ClipData mClipData = result.getData().getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
String imageFilePathColumn = getPathFromURI(this, uri);
productImagesList.add(imageFilePathColumn);
}
} else {
if (result.getData().getData() != null) {
Uri mImageUri = result.getData().getData();
String imageFilePathColumn = getPathFromURI(this, mImageUri);
productImagesList.add(imageFilePathColumn);
}
}
} else {
showToast(this, "You haven't picked Image");
productImagesList.clear();
}
} else {
productImagesList.clear();
}
} catch (Exception e) {
e.printStackTrace();
showToast(this, "Something went wrong");
productImagesList.clear();
}
});
}
and getPathFromURI() is method which define below
public String getPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = getPath();
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
and the getPath() is
private File getPath() {
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
if (!folder.exists()) {
folder.mkdir();
}
return new File(folder.getPath(), System.currentTimeMillis() + ".jpg");
}
I'm making an App where I call the file explorer, the when I choose a file i get the name with file.getName() and put it in a TextView and get the path with file..getPath() and save it in a String, this String I use it to attach the file into a mail... my problem is that when a choose a file like .PDF, .DOC, .DOCX, .MP3 I can attach it but when a select an image I get this kind of path: "/media/external/images/media/1220" and does not attach anithing, I've been serarching everywhere and use almost every option I have found with no result.
Here is my code:
private void PickFile(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICKER);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((resultCode == RESULT_OK) && (requestCode == PICKER)) {
String FilePath = data.getData().getPath();
File file = new File(FilePath);
}
if (txtAdjunto1.getText() == "_") {
adjunto1 = file.getPath();// I get the path to add it to the MimeBodyPart
txtAdjunto1.setText(file.getName());// I put the name in the TextView
I've been trying this:
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
int column_index;
String ruta = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null){
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ruta = cursor.getString(column_index);
}
return ruta;
} finally {
if (cursor != null) {
cursor.close();
}
}
But the app crashes when I pick the file.
Also tried this:
file = new File(file.getAbsolutePath());
But still geting this "/media/external/images/media/1220"...
Hop someone can help me with this, and thanks in advance
ACTION_GET_CONTENT and ACTION_OPEN_DOCUMENT allow the user to choose a piece of content. That content might be a local file. That content might also be:
Something on a file server on the network
Something in a cloud storage service, such as Google Drive
Something in an encrypted volume
Something that is a file, but is not a file that you can access directly
And so on
You have two main options. If you only want files, then use a third-party file chooser library to replace all of the code in your question.
Or, you can take the Uri that you get from data.getData() in onActivityResult() and do two things with it:
First, use DocumentFile.fromSingleUri() to get a DocumentFile object pointing to that Uri. You can call getName() on the DocumentFile to get a "display name" for the content, which should be something that the user will recognize.
Then, use a ContentResolver and openInputStream() to get at the content itself, similar to how you might use a FileInputStream to get at the bytes in a file.
Try this...
The following code is to select any type of file from file manager and camera then convert to byte array and attach file make edit as per your requirement
private void selectFile() {
final CharSequence[] items = {"Camera", "Choose from File Manager",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(ComposeActivity.this);
builder.setTitle("Add Attachment!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Constant.checkPermission(ComposeActivity.this);
if (items[item].equals("Camera")) {
userChoosenTask = "Camera";//String
if (result)
cameraIntent();
} else if (items[item].equals("Choose from File Manager")) {
userChoosenTask = "Choose from File Manager";//String
if (result) {
FileManagerIntent();
}
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
to call camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
file from file manager
private void FileManagerIntent() {
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), 111);
} catch (Exception e) {
// Handle exceptions here
e.printStackTrace();
}
}
results
#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);
}
}
getting camera result and converting it to bytearray
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");
Uri uri = Uri.fromFile(destination);
String uriString = uri.toString();
String path = destination.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = destination.getName();
}
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
fileByteArray = bytes.toByteArray();
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Soma", strFile);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
result from file manager
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
if (uri.toString().contains("video") || uri.toString().contains("audio")) {
Toast.makeText(ComposeActivity.this, "Oops! can't send video/audio file", Toast.LENGTH_SHORT).show();
} else {
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = myFile.getName();
}
Log.v("Super DisplayName", strFileName);
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
InputStream iStream = getContentResolver().openInputStream(uri);
fileByteArray = getBytes(iStream);
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
file to bytearray
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
I want to save the image without compressing it and want to save it in it's original form i.e. when image is compressed the image size decreases and image become small. I am using native camera for this purpose. I am working in android studio. I am making an app in which i am using a camera to save image. But the image is compressed and is very small and very lower quality.
Below is my code for saving image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
Bitmap bmp = (Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
if(isStoragePermissionGranted())
{
SaveImage(bitmap);
}
}
}else {
switch (requestCode) {
case 1000:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
getLocation();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(this, "Location Service not Enabled", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
}
private void SaveImage(Bitmap finalBitmap) {
File storageDir = new File (String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
String root = storageDir + Environment.getExternalStorageDirectory().getAbsolutePath().toString();
Log.v(LOG_TAG, root);
File myDir = new File(root + "/captured_images");
if (!myDir .exists())
{
myDir .mkdirs();
}
Random generator = new Random();
int n = 1000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir,fname);
try {
file.createNewFile();
MediaScannerConnection.scanFile(getApplicationContext(), new String[] {file.getPath()} , new String[]{"image/*"}, null);
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Update 1
For more understanding i am putting my onClick method
btn_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check permission for camera
if(ActivityCompat.checkSelfPermission(MainActivity.this, CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
// Check Permissions Now
// Callback onRequestPermissionsResult interceptado na Activity MainActivity
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{CAMERA},
MainActivity.REQUEST_CAMERA);
}
else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
}
}
});
I searched the solution and found that i can use AndroidBitmapUtil
class so i copy and pasted this class into my project i.e. i created a new class. But i don't know how to use it. Although it is described that i can save image by doing new AndroidBmpUtil().save(bmImage, file);. But again i can't match with my code :(
Any help would be highly appreciated
new AndroidBmpUtil().save(source, sdcardBmpPath);
USER ABOVE LINE OF CODE AND FOLLOW BELOW LINK
https://github.com/ultrakain/AndroidBitmapUtil
Open Camera and save image into some specific directory.
solution number 1
private String pictureImagePath = "";
private void openBackCamera() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
File file = new File(pictureImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 1);}
Handle Image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
File imgFile = new File(pictureImagePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
solution number 2
I have used the following code and this works perfectly fine for me.
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
and also
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and
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);
}
For opening camera use
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "imagename.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
and in your onActivityresult method use
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("imagename.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
yourimageview.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
i am not able to store the path and image into database, i want to store path or image into database and i want to fetch that image and set to imageview after updating profile..here is my onactvity result please help me.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
ImagePaht = CommonUtility.encodeTobase64(bitmap);
mAddProfilePic.setImageBitmap(bitmap);
mAddProfilePic.setScaleType(ImageView.ScaleType.MATRIX);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
boolean delete = f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byteArray = stream.toByteArray();
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
// Log.e("path of ", picturePath + "");
ImagePaht = CommonUtility.encodeTobase64(thumbnail);
mAddProfilePic.setImageBitmap(thumbnail);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
mAddProfilePic.setScaleType(ImageView.ScaleType.MATRIX);
}
}
}
//this my method to save in database
private void saveInDbHospitalTable() {
Log.e("file name", "" + ImagePaht);
Table_Hospital_Methods mTable_Hospital_Methods = new Table_Hospital_Methods(getApplicationContext());
//String profilePictureURL = String.valueOf(byteArray);
// Log.e("profilePictureURL", "" + profilePictureURL);
String hospitalName = mHospitalName.getText().toString();
String doctorName = mDocName.getText().toString();
String registrationNo = mRegistrationNumber.getText().toString();
String hospitalPhoneNumber = mHospitalPhoneNumber.getText().toString();
String doctorPhoneNumber = mDoctorPhoneNumber.getText().toString();
String hospitalAddress = mHospiatlAddress.getText().toString();
ModelHospitalProfile modelHospitalProfile = new ModelHospitalProfile(byteArray, hospitalName,
doctorName, registrationNo, hospitalPhoneNumber, doctorPhoneNumber, hospitalAddress);
long hospitalId= mTable_Hospital_Methods.gethospitalId();
Log.e("hospitalId", "" + hospitalId);
if(mTable_Hospital_Methods.getHospitalCount()>0 && userName1==1) {
mTable_Hospital_Methods.updateToDo(modelHospitalProfile,hospitalId);
Log.e("update", "update");
}
else{
mTable_Hospital_Methods.insertHospital(modelHospitalProfile);}
}
For storing image into your database, you can either save image path or can save Base64 image into your database
Here, we are storing image path into database
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
settingImaePath(fileUri);
}
}
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
Log.i("file path", "" + filePath);
final Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
File imageFile = null;
String mPath = null;
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + now.getTime() + ".jpg";
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
UserProfile userProfile = new UserProfile();
userProfile.setImagePath(mPath);
ProfileTable.getInstance().add(signupBean); // Here setting gallery image path into ProfileTable
userImage.setImageBitmap(bitmap); // userImage is an Imageview
} catch (IOException e) {
e.printStackTrace();
}
}
public void settingImaePath(Uri fileUri) {
String filePath = fileUri.getPath();
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(filePath);
}
}
private void previewMedia(String filePath) {
// Checking whether captured media is image or video
Log.i("file path", "" + filePath);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throw s OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
File imageFile = null;
String mPath = null;
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + now.getTime() + ".jpg";
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 80;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
UserProfile userProfile = new UserProfile();
userProfile.setImagePath(mPath);
ProfileTable.getInstance().add(signupBean); // Here setting gallery image path into ProfileTable
userImage.setImageBitmap(bitmap);
}
//For Viewing save image from path
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
I try to select an image from gallery and saved in parse cloud server in android.
But I am unable to do.
I have tried the following code:
OnImageView Click event choose image:
imageDish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
} catch (Exception e) {
Toast.makeText(getActivity(),
"Select Image From Gallery", Toast.LENGTH_LONG)
.show();
// TODO: handle exception
}
}
});
OnActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
imageDish.setImageURI(selectedImageUri);
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Parse Code for save image:
InputStream imageStream = null;
try {
imageStream = getActivity().getContentResolver().openInputStream(
selectedImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
ParseFile file = new ParseFile("FoodImage", image);
// Upload the image into Parse Cloud
file.saveInBackground();
Log.d("File======", "" + file);
try {
ParseObject Foodobject = new ParseObject("Food");
Foodobject.put("FoodName", Name);
Foodobject.put("ResId", ParseObject.createWithoutData("Restaurant",Res_id);
Foodobject.put("FoodCategory", ParseObject.createWithoutData("FoodCategory", _CategoryId));
Foodobject.put("FoodDesc", Des);
Foodobject.put("Price",priceNumber);
Foodobject.put("VegOnly", "Y");
Foodobject.put("IsRecommended", false);
Foodobject.put("FoodImage", file);
Foodobject.saveInBackground();
} catch (Exception ex) {
Log.e("Error", "" + ex);
}
Here is my log output:
File======: com.parse.ParseFile#39f19700
Replace your code with this
ParseFile file = new ParseFile("FoodImage.png", image);
In parse docs it is clearly mentioned that you give a name to the file that has a file extension. This lets Parse figure out the file type and handle it accordingly.
https://parse.com/docs/android/guide#files
i think your issue on image size, it might be your selected image from gallery is too large to save in parse.com
so try this code.
It is working for me .
ByteArrayOutputStream stream = null;
Bitmap bitmap = BitmapFactory.decodeFile(picturePath)
Bitmap newbitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
stream = new ByteArrayOutputStream();
newbitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
final ParseFile file = new ParseFile("FoodImage.png", image);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null){
// Your Parse Code....
}
}