this my code its not working how pick up image from gallery and display in imageview
public class MainActivity extends ActionBarActivity {
Button imageUpload;
ImageView imageView;
static final int PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
imageUpload= (Button) findViewById(R.id.buttonImage);
imageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,PICTURE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case PICTURE:
if(requestCode==RESULT_OK){
Uri uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(prjection[0]);
String path=cursor.getString(columnIndex);
cursor.close();
Bitmap selectFile = BitmapFactory.decodeFile(path);
Drawable d = new BitmapDrawable(selectFile);
imageView.setBackground(d);
}
}
}
hello friends i am new in android i required this type of apps to upload image and display in imageview plz help me if have idea.thanks in advance
Finnay this Code is working and we can give fixed size of imageview that display in particular area
layout.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image Upload"
android:id="#+id/buttonImage"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_x="13dp"
android:layout_y="112dp" />
Main Activity
Button imageUpload;
ImageView imageView;
static final int PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
imageUpload= (Button) findViewById(R.id.buttonImage);
imageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,PICTURE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==PICTURE && resultCode==RESULT_OK && null !=data)
{
Uri uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(prjection[0]);
String path=cursor.getString(columnIndex);
cursor.close();
Bitmap selectFile = BitmapFactory.decodeFile(path);
Drawable d = new BitmapDrawable(selectFile);
imageView.setBackground(d);
// imageView.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
Finally this code is working
Replace
Bitmap selectFile = BitmapFactory.decodeFile(path);
Drawable d = new BitmapDrawable(selectFile);
imageView.setBackground(d);
To
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
use this code
uploadPic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(yourActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) { Intent intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE); File f = new
File(android.os.Environment.getExternalStorageDirectory(),
"temp.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f)); startActivityForResult(intent, 1); } else
if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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 {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
pic.setImageBitmap(bitmap);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix"
+ File.separator + "default";
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);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException 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);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
bitmap = (BitmapFactory.decodeFile(picturePath)); Log.w(
"path of image from gallery......******************........."
, picturePath+""); pic.setImageBitmap(bitmap);
decodeFile(picturePath);
}
}
}
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 = 300;
// 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);
pic.setImageBitmap(bitmap);
}
for more help ... go to this link
Also, in onActivityResult, the switch and if statements are both checking for requestCode. Therefore the if is never true.
Replace
if(requestCode==RESULT_OK)
with
if(resultCode==RESULT_OK)
Related
I was selected the image after it have to set it in the imageview.But it doesn't set it in imageview.
I have posted the relevant code.
EditViewProfileActivity.java
public class EditViewProfileActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final int CAMERA_PICTURE = 1;
private static final int GALLERY_PICTURE = 2;
File destination = null;
String filePath = null;
Bitmap chosenImage;
String imgSelected = null;
ImageView dateBirthImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_view_profile_activity);
galImageView = (ImageView) findViewById(R.id.gallery_image_edit_view);
galImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosePictureAction();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE
&& resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
destination = new File(selectedImagePath);
filePath = selectedImagePath;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
chosenImage = BitmapFactory.decodeFile(selectedImagePath, options);
if (chosenImage != null) {
imgSelected = "fulFilled";
galImageView.setImageBitmap(chosenImage);
Log.e("ChosenImage", "" + chosenImage);
}
} else if (requestCode == GALLERY_PICTURE
&& resultCode == RESULT_CANCELED) {
}
}
private void choosePictureAction() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(EditViewProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PICTURE);
} else if (items[which].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_PICTURE);
} else if (items[which].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
I dont know why selected image not showing in imageview.Anyone can help me with this.Thank you.
I Have use this code:
private void openGallery() {
Intent gallery =
new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
Uri imageUri = data.getData();
try {
bitmaps = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmaps.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] byteArray = stream.toByteArray();
encodeded = Base64.encodeToString(byteArray, Base64.DEFAULT);
byte[] decodedString = Base64.decode(encodeded, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
userinfoimage.setImageBitmap(bitmaps);
new UploadImage().execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you only want to set image in imageview. you can directly use the uri. Like this
String stringUri = selectedImageUri.getPath();
galImageView.setImageURI(null);
galImageView.setImageURI(Uri.parse(stringUri));
I am working on an Android project in which I have the functionality where user can click on the a button and it will open the camera to upload the image. The upload button is hidden until there is image taken and shown in preview.
What I would like to do is to use the same upload button, which I have set to visible by default now and on clicking it, I would like to open a gallery, which the user can then use to select an image, and it would be shown in preview.
I have a boolean flag to manage this, where if the flag is false, then gallery is opened, else the image in the preview is uploaded.
I have this, but I don't know how to open a gallery and then send the image to preview, to upload. I am new to Android programming, so kindly take that into consideration.
I searched for similar functionality, but the problem is, I have not found, where such features are integrated.
Java code :
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private static boolean galleryFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if(!galleryFlag){
// I think the gallery open code should come here.
}
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
}else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if(!(reducedSizeBitmap == null)){
if(reducedSizeBitmap == null){
Log.d("Image bitmap"," Is null");
}
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
}
}
}
I hope this much information is enough. Can anyone point me which functions I should put and where. Thanks a lot. :-)
Edit with Answer
Finally the integration works. I had to combine answers from the one I received and here on SO.
Final Code
public class AddPhotosForRestaurant extends RestaurantDrawerActivity {
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
private Uri imageToUploadUri = null;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private boolean galleryFlag = false;
private boolean uploadNow = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
set(null, null);
final RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox) findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if (uploadNow) {
uploadNow = false;
galleryFlag = true;
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
}
if (!galleryFlag) {
galleryFlag = true;
uploadNow = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GALLERY_INTENT_REQUEST_CODE);
} else {
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
return b;
} catch (IOException e) {
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if (imageToUploadUri != null) {
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if (reducedSizeBitmap != null) {
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
}
if (requestCode == GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
Uri selectedImage = Uri.parse(data.getDataString());
reducedSizeBitmap = MediaStore.Images.Media.getBitmap(
getApplicationContext().getContentResolver(),
selectedImage);
ImgPhoto.setImageBitmap(reducedSizeBitmap);
} catch (Exception e) {
Toast.makeText(this, "Error while selecting Image", Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if (!(reducedSizeBitmap == null)) {
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray, profilePhoto);
}
}
}
Thanks a lot for all your help.. :-)
In Constant file write in my case(ActivityConstantUtils.java)
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
To open Gallery & get path of selected image use following code :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
After that you get path in onActivityResult() method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
String imagePath = getFilePath(data);
// TODO: Here you set data to preview screen
}catch(Exception e){}
}
}
private String getFilePath(Intent data) {
String imagePath;
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]);
imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
I am creating a chatting app. and i what to send content(Image, Video, Audio, Location, Contact) in Private and Group. for sending image i used this code
attachInfoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendImage();
}
});
selectImage();
}
private void sendImage(){
File filePhoto = fileUpload;
System.out.println("Send Image..>>"+fileUpload);
Boolean fileIsPublic = true;
QBContent.uploadFileTask(filePhoto, fileIsPublic, null, new QBEntityCallbackImpl<QBFile>() {
#Override
public void onSuccess(QBFile file, Bundle params) {
String publicUrl = file.getPublicUrl();
System.out
.println("==========image uploaded success++++++++"
+ publicUrl);
Integer id = file.getId();
System.out
.println("===================image id+++++++++++"
+ id + "");
// create a message
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
// attach a photo
QBAttachment attachment = new QBAttachment("photo");
attachment.setId(file.getId().toString());
chatMessage.addAttachment(attachment);
// send a message
// ...
Intent a =new Intent(ImageFileAttachActivity.this, ChatActivity.class);
startActivity(a);
}
#Override
public void onError(List<String> errors) {
// error
}
});
// Intent a =new Intent(ImageFileAttachActivity.this, ChatActivity.class);
// startActivity(a);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
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);
attachInfoImage.setImageBitmap(bitmap);
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
ImageFileAttachActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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);
}
}
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");
fileUpload=destination;
// new ProfilePicUpload().execute();
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
attachInfoImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
fileUpload = new File(selectedImagePath);
// new ProfilePicUpload().execute();
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
attachInfoImage.setImageBitmap(bm);
}
and I am successfully send Image to the QuickBlox server.and want to get this image for this code...
///////////////////// Download Image\\\\\\\\\\\\\\\\\\
#SuppressWarnings("deprecation")
public void processMessage(QBChat chat, final QBChatMessage chatMessage) {
for(QBAttachment attachment : chatMessage.getAttachments()){
final String fileId = attachment.getId();
QBContent.downloadFile(fileId, new QBEntityCallbackImpl<InputStream>() {
#SuppressWarnings("unused")
public void onComplete(Result result) {
if (result.isSuccess()) {
QBFileResult fileResult = (QBFileResult) result;
QBFile file = fileResult.getFile();
String fileURL = file.getPublicUrl();
}
}
});
}
}
But when i want to get that image then its create null pointer error.. i can't understand. where i'm wrong can you Please... and also provide example to create send content(Video, Audio, Location, Contact). Please Help me.
Hi I have created an Activity from that I am calling startActivityForResult at the first time it is working below is the code
Dialog box for choosing image from Camera or Gallery
private void selectImage() {
System.out.println("Select Image");
final CharSequence[] items = { "Take Photo",
"Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
} else if (items[item]
.equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
intent, ""), PICK_IMAGE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
It's onActivityForResultSetMethod
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("onActivityResult");
System.out.println("requestCode : - " + requestCode);
System.out.println("resultCode : - " + resultCode);
System.out.println("data : - " + data);
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
imagePath = getAbsolutePath(data.getData());
bitmap = decodeFile(imagePath);
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
ivUpload.setImageBitmap(bitmap);
} else if (requestCode == CAPTURE_IMAGE) {
imagePath = getImagePath();
bitmap = decodeFile(imagePath);
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
ivUpload.setImageBitmap(bitmap);
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
Issue if when i first time called, In image view i am not getting image, and also if i tried it again
Activity's onCreate method is also called don't know but why
Try this way,hope this will help you to solve your problem.
private int PICK_IMAGE=1;
private int CAPTURE_IMAGE=2;
private String imgPath;
private void selectImage() {
System.out.println("Select Image");
final CharSequence[] items = { "Take Photo",
"Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
} else if (items[item]
.equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
ivUpload.setImageBitmap(decodeFile(getAbsolutePath(data.getData())));
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
} else if (requestCode == CAPTURE_IMAGE) {
ivUpload.setImageBitmap(decodeFile(getImagePath()));
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
}
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;
}
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
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 = 1024;
// 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;
}
Note : please not forget this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try This : I have done some modification.It is working on my end
public class MainActivity extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btnSelectPhoto);
viewImage = (ImageView) findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is
// present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp1.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "AudioBlog" + File.separator + "default";
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);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException 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);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........",
picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
try this
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
private void selectImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(
ProfileActivity.this);
// builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Take a Photo",
"Choose from Gallery" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent1 = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent1, CAPTURE_IMAGE);
break;
case 1:
// GET IMAGE FROM THE GALLERY
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
break;
default:
break;
}
}
});
builder.show();
}
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
onActivityForResultSetMethod
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
System.out.println("path" + selectedImagePath);
imageView.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
System.out.println("path" + selectedImagePath);
imageView.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 };
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;
}
As to called onCreate(), please Log.d("~~~",""+savedInstanceState);, it will likely be non-null meaning that Android advices you to restore the application state from the bundle.
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);
}