I m selecting Image From Gallery and crop in My Phone And Uploading To Server ..
When i m testing Someother devices then
image was Unable Picked to some devices
public void selectImageFromGallery() {
String TEMP_PHOTO_FILE = "temporary_holder.jpg";
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, PICK_IMAGE);
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),"temporary_holder.jpg");
try {
file.createNewFile();
} catch (IOException e) {}
return file;
} else {
return null;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
File tempFile = getTempFile();
String filePath= Environment.getExternalStorageDirectory()
+"/"+"temporary_holder.jpg";
System.out.println("path "+filePath);
decodeFile(filePath);
if (tempFile.exists()) tempFile.delete();
}
}
}
}
/**
* The method decodes the image file to avoid out of memory issues. Sets the
* selected image in to the ImageView.
*
* #param filePath
*/
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
roundedImage=new RoundedImage(bitmap);
image.setImageDrawable(roundedImage);
}
here Is My Code
please Tell ME Where I m Doing Wrong
I want To Remove To Create An New File On Sd Card if Sd Card Is Not Available on no space
app Crashed
//Initialize variable
int select_photo = 1;
//Make this method to start intent
void Profile_Image_Pick() {
Intent in = new Intent(Intent.ACTION_PICK);
in.setType("image/*");
startActivityForResult(in, select_photo);
}
//Now on ActivityforResult
#Override
protected void onActivityResult(int requestCode, int resultCode,
super.onActivityResult(requestCode, resultCode, imagereturnintent);
switch (requestCode) {
case select_photo:
if (resultCode == RESULT_OK) {
final Uri imageuri = imagereturnintent.getData();
final InputStream imageStream = getContentResolver()
.openInputStream(imageUri);
bitmap = BitmapFactory.decodeStream(imageStream);
Bitmap bt = Bitmap.createScaledBitmap(bitmap, 70, 70, false);
profile_image.setImageBitmap(bt);
}
}
}
//for checking sdcard is present or not you can use
if(android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
//sdcard present
else
//not present
and finally call the starting method.
Hope it helps.
Related
I found some code on SO helping me bring up an image selector, save the image, re-size/decode it and display it in an ImageView, however I am wanting to know how to save this newly re-sized image into a different folder in the Gallery and then return it's new location (including the filename) as a String. Here is what I have so far:
Starting the image picker intent:
public void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
Getting the selected image:
#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();
InputStream imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = decodeUri(selectedImage);
imageIcon.setImageBitmap(yourSelectedImage);
imageText.setText("");
} catch (Exception e) {
Toast.makeText(this, "Image Selection Error", Toast.LENGTH_LONG).show();
}
}
}
}
Function to decode the image:
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 200;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
I am also unsure whether I have correctly implemented this decode function as changing the REQUIRED_SIZE int makes no difference when it's displayed in the ImageView.
I managed to solve this with the below method:
public void saveResizedImage(Bitmap image) {
File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "rapical" + File.separator);
String path = root.getPath();
OutputStream fOut = null;
File noOfImages[] = root.listFiles();
int fileCount = 0;
for (int i = 0; i < noOfImages.length; i++) {
fileCount++;
}
File foodImageFile = new File(path, "rapical" + fileCount + ".png");
try {
fOut = new FileOutputStream(foodImageFile);
image.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
String imagePath = path + "/rapical" + fileCount + ".png";
Log.w("ImagePath: ", imagePath);
} catch (Exception e) {
}
}
I'm having a simple problem that may seem easy, however, when I pick a image from the gallery and try to set it up the in imageview in onActivityResult, the error would show up.
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/35 }} to activity {com.mypackagename/com.mypackagename.SQLiteActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This error must be due to the null object. That would mean that no data was retreived? I percieve that the settings that I made had no problem, however, I may have missed something. I've set the sample code below.
This is the code that calls the gallery
public void settingImage(View v){
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
This code is for getting the results
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
// Log.d("Path", picturePath);
//sampleimage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
// imgPath = picturePath;
icontext.setText(picturePath);
cursor.close();
} else {
}
}
Here's some settings
private static int RESULT_LOAD_IMAGE = 1;
basic sdk setup
minSdkVersion 14
targetSdkVersion 22
I have try this to get Bitmap,
code that calls the gallery picker,
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
getting the results of bitmap,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
//yourSelectedImage = BitmapFactory.decodeStream(imageStream);
try {
yourSelectedImage = decodeUri(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// imgViewProfilePic.setImageBitmap(yourSelectedImage);
}
}
}
to decode uri,
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 140;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
I want to get an image from a gallery to show in imageview. Intent returned the path as "Content" in Sony mobile. I can get it using this code.
Uri image=data.getData();
But when I am using a Samsung mobile, intent returned this.
Intent { act=file:///mnt/sdcard/Pictures/Education%20App/IMG_20140513_160840.jpg (has extras) }
I used same code to get the URI, but the returned value is null. I don't know how to get this Uri.
I have demonstrate to Both the case
1) capture Photo from camera
2) Take a photo from gallary
Try this is working like charm with me
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
btnGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
}
});
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
Upload Image Application: It is working fine on emulator but unable to upload Image on test phone. It chooses pic from gallery but doesnt display anything in Imageview.
public class Uploadimage extends Activity {
public static int requestCode=1;
Button b1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadimage);
b1= (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, requestCode);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data) ;
if (requestCode==1 && resultCode==RESULT_OK) {
Uri image = data.getData();
String [] filepath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(image, filepath, null, null, null);
cursor.moveToFirst();
int column = cursor.getColumnIndex(filepath[0]);
String path= cursor.getString(column);
cursor.close();
ImageView imageview= (ImageView) findViewById(R.id.imageView1);
imageview.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
Use the following method for decoding your file path.
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 4;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bmp = BitmapFactory.decodeFile(filePath, o2); // this bmp object of Bitmap is global and you can set it to your ImageView.
}
Now you can call this function after this one
String path= cursor.getString(column);
decodeFile(path);
If your get the content from the mobile, below code must write in manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
use this below code you will get the solutions..
`buttonLoadImage.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Uri targetUri = data.getData();
Bitmap bitmap;
try
{
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}`
I am little confusion about how to get image name, when taking photo from camera(Current Click image) or sd card(Already cliked or in the sd card image).Could you please help me out how to get image name.
if (requestCode == CAMERA_REQUEST) {
ImageView profImage;
Bitmap photo = (Bitmap) data.getExtras().get("data");
Bitmap scaledphoto = Bitmap.createScaledBitmap(photo, height, width,
true);
profImage.setImageBitmap(scaledphoto);
//How to get name here
}
Now , Here How to get ImageName for propose of saving image on database.
Or
Imageview test=(Imageview) findViewById(R.id.testimage);
test.setImageResource(R.drawable.androidimage);
So, I want get name of image, Here image name is androidimage.SO How to get imagename.
You can pass the Bitmap to this method to get Image Uri.
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(),
inImage, "Title", null);
return Uri.parse(path);
}
Finally you can set the image to image view with
imageView.setImageUri(mUri);
Please use the following code.
public class UploadImageActivity extends Activity {
private final int CAMERA_PICTURE = 1;
private final int GALLERY_PICTURE = 2;
private ImageView userPictureImageView;
private Intent pictureActionIntent = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
userPictureImageView = (ImageView) findViewById(R.id.imageView1);
userPictureImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE) {
Uri uri = data.getData();
if (uri != null) {
// User had pick an image.
Cursor cursor = getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
File photos = new File(imageFilePath);
Bitmap b = decodeFile(photos);
b = Bitmap.createScaledBitmap(b, 150, 150, true);
userPictureImageView.setImageBitmap(b);
cursor.close();
}
else {
Toast toast = Toast.makeText(this, "No Image is selected.", Toast.LENGTH_LONG);
toast.show();
}
}
else if (requestCode == CAMERA_PICTURE) {
if (data.getExtras() != null) {
// here is the image from camera
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
userPictureImageView.setImageBitmap(bitmap);
}
}
}
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {
}
return null;
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent, CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
}
Dont forget to add the camera permission in your manifest file.
Updated Code
Gallery :
Intent photoPickerIntent = new Intent(
Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, CAMERA_PIC_REQUEST);
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
Uri selectedImage = data.getData();
String filePath = getRealPathFromURI(selectedImage);
// used in show HD images
BitmapFactory.Options bounds = new BitmapFactory.Options();
// divide bitmap to 4 sample size it can be 2rest(2,4,8 etc)
bounds.inSampleSize = 4;
// get bitmap from bounds and file path
Bitmap bmp = BitmapFactory.decodeFile(filePath, bounds);
imageView.setImageBitmap(bmp);
Uri selectedImageUri1 = data.getData();
String path = getRealPathFromURI(selectedImageUri1);
File file = new File(path);
textView.setText(file.getName());
}
}
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);
}