I want to allow user to upload image from gallery into an android application that i am creating. At the moment i am able to allow the user to chose the image from the gallery here in the codes below:
/* Choose an image from Gallery */
void openImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
Then onActivityResult i try to get the path of the image and convert it into URI then i later convert it into into Bitmap to display to the user in my codes below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
profileImage.setImageURI(selectedImageUri);
}
final InputStream imageStream;
try {
assert selectedImageUri != null;
imageStream = getContentResolver().openInputStream(selectedImageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
encodedImage = encodeImage(selectedImage);
Log.i("encodedImage", encodedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
public String getPathFromURI(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;
}
private String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
On click of this button below i want to save the encoded image into SharedPreferences so when the user starts the application again i can show that image to the user but unfortunately i am unable to get the encoded image and i don't know how to set it on onCreateView method.
btnAddImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("image", encodedImage);
editor.apply();
showSnackSuccess();
}
});
Related
public static final int TAKE_PHOTO=1;
public static final int CROP_PHOTO=2;
private Button choosePhoto;
private ImageView picture;
private Uri imageUri;
choosePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File outputImage = new File(Environment.getExternalStorageDirectory(),"output_image.jpg");
try {
if (outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,CROP_PHOTO);
}
});
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
switch (requestCode){
case CROP_PHOTO:
if (resultCode==RESULT_OK){
try{ //使用decodeStream()函数 解析成Bitmap对象,
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
break;
default:break;
}
}
Taking photo is OK but choose photo is wrong, when I click the button it shows album successfully, but when selecting a picture, it return whitout choosing that picture.
Use below code in onActivityResult();
Uri filePath = intent1.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), filePath );
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
picture.setImageBitmap(bitmap);
Paste below code after getting data from intent in onactivityresult.
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
profilePic.setImageBitmap(BitmapFactory.decodeFile(picturePath));
I am trying to make an app to select an image from the gallery or google photos and then crop it to make it my app background. The problem I am facing is that When I try to crop the picture using google photos then it gets saved but the app background doesn't change and I don't recive any crashes or any errors but when I crop it using the gallery app everything seems to work perfectly.
Here is my code to select photos:
Intent i = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
case SELECT_PICTURE: {
if (resultCode == RESULT_OK && null != data) {
mHandler.post(new Runnable() {
#Override
public void run() {
Uri selectedImageUri = data.getData();
InputStream imageStream;
Bitmap selectedImage;
try {
cropCapturedImage(getImageUrlWithAuthority(getApplicationContext(),selectedImageUri));
} catch (ActivityNotFoundException aNFE) {
//display an error message if user device doesn't support
showToast(getString(R.string.error_crop_not_supported));
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(getImageUrlWithAuthority(getApplicationContext(),selectedImageUri), filePathColumn, null, null, null);
cursor.moveToFirst();
imageStream = getContentResolver().openInputStream(getImageUrlWithAuthority(getApplicationContext(),selectedImageUri));
selectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//SharePreference to store image
PrefManager.putString(Constant.IMAGE_DATA, encodedImage);
cursor.close();
//set gallery image
setChatBackground();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
}
Here is my cropIntent code:
public void cropCapturedImage(Uri picUri) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 9);
cropIntent.putExtra("aspectY", 14);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PICTURE);
}
ase CROP_PICTURE: {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String yourRealPath = cursor.getString(columnIndex);
} else {
//boooo, cursor doesn't have rows ...
}
cursor.close();
String v= data.toString();
if (resultCode == RESULT_OK && null != data) {
mHandler.post(new Runnable() {
#Override
public void run() {
try {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//SharePreference to store image
PrefManager.putString(Constant.IMAGE_DATA, encodedImage);
//set gallery image
setChatBackground();
} catch (NullPointerException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
});
}
No, Android Does Not Have a Crop Intent
Calling method startActivity() on an Intent with an action of com.android.camera.action.CROP. They are doing this to crop an image.
This is a really bad idea.
Source here - CommonsBlog
Try to log your selectedImageUri first.
I suspect that the google photos returns a url to online file, while the gallery app return a local file path.
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();
}
}
I'm trying to get an image from the Gallery and send it to a server.
I do get an base64 encoded string but it's a thin line, not the whole image.
For example, I used Motobit to decode this random image. The base64 string I got
works fine. But the encoded string that I get from my app for the same image is really smaller and when you convert into an image it becomes this.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
try {
Uri selectedImage = imageReturnedIntent.getData();
String imageStream = getRealPathFromURI(context, selectedImage);
Bitmap bitmap = BitmapFactory.decodeFile(imageStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e(LOG_TAG, encodedString);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
What is making my encodedString becomes only a piece of the image? Thanks!
Maybe the string is correct but the Log method has a character limit.
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....
}
}