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));
Related
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();
}
});
I know this may be asked before and I tried with all the answers given here but it's not working.
I pick an image from gallery ,show it, then change some pixels and try to save it in sd card but it's not saved .
Layout :
<Button
android:id="#+id/pick_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Image" />
<ImageView
android:id="#+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
.java file
Button buttonLoadImage = (Button)
rootView.findViewById(R.id.pick_image_button);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_PICK);
File pictureDirectory=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);
pictureDirectoryPath=pictureDirectory.getPath();
Uri data=Uri.parse(pictureDirectoryPath);
i.setDataAndType(data,"image/*");
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK
) {
try{
imageUri = data.getData();
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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
catch (Exception e) {
e.printStackTrace();
}
Utility.showCustomAlert(picturePath,getActivity(),"error");
imageView = (ImageView) rootView.findViewById(R.id.image_view);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
try{
inputstream =
getContext().getContentResolver().openInputStream(imageUri);
Bitmap bmp = BitmapFactory.decodeStream(inputstream);
imageView.setImageBitmap(bmp);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Code to save the image (It's not the full code but the part to save it)
String sdCardDirectory =
Environment.getExternalStorageDirectory().getAbsolutePath();
File dir = new File(sdCardDirectory+ "/download");
dir.mkdirs();
String fname="imazh.png";
File file=new File(dir,fname);
if(file.exists())file.delete();
// Encode the file as a PNG image.
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
MediaScannerConnection.scanFile(getContext(),
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
I've added the permission in manifest file
Can someone help me understand how to use OnPause() and OnResume() in this code? I'm trying to save last Selected or Captured image in imageView so when the user closes the program and comes back again he doesn't need to set or take the image again.
package com.example.thang.sdcardimagesactivity;
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
Button button;
ImageView imageView;
String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
imageView=(ImageView) findViewById(R.id.image);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Switch();
return true;
}
});
}
public void Switch(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==REQUEST_CODE&&resultCode== Activity.RESULT_OK){
try{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Log.v("roni", filePath);
cursor.close();
if(bitmap != null && !bitmap.isRecycled())
{
bitmap = null;
}
bitmap = BitmapFactory.decodeFile(filePath);
//imageView.setBackgroundResource(0);
imageView.setImageBitmap(bitmap);
}catch (Exception e){
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);};
#Override
protected void onPause() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
SharedPreferences.Editor editor = sp.edit();
editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
super.onPause();
}
#Override
protected void onResume() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(myBitmap);
super.onResume();
}
}
View Activity
public class ViewActivity extends Activity {
ImageButton imageViews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
imageViews = (ImageButton) findViewById(R.id.image);
// textView=(TextView) findViewById(R.id.textview);
Intent intent = getIntent();
Uri data = intent.getData();
if (intent.getType().indexOf("image/") != -1)
{
imageViews.setImageURI(data);
}
setResult(RESULT_OK, intent);
Bundle bundle=new Bundle();
bundle.putInt("image",R.id.image);
intent.putExtras(bundle);
finish();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
You can save an image to the SD card so it can be permanently accessed. It's best you do this immediately in the onActivityResult() method.
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "ImagesFolder");
File file = new File(imagesFolder, "image.jpg");
String fileName = file.getAbsolutePath();
try {
FileOutputStream out = new FileOutputStream(file);
squareBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("Image", "Convert");
}
And to load it back when you restart the application (in onCreate or preferably in onResume):
try {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "ImagesFolder");
if (!imagesFolder.exists())
imagesFolder.mkdirs();
if (new File(imagesFolder, "image.jpg").exists()) {
String fileName = new File(imagesFolder, "image.jpg").getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(fileName);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
}
} catch (NullPointerException e) {
Log.e("Exception", "null");
}
Of course you can change the folder and image name.
I'm trying to save an image loaded from the gallery to the phone memory(local path). Can anyone guide me into this?
This is how I get the image from the gallery.
ImageView profilePicture;
private Uri imageUri;
String picturePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
profilePicture = (ImageView) findViewById(R.id.profile_picture);
profilePicture.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN: {
break;
}
case MotionEvent.ACTION_UP:{
uploadImage();
break;
}
}
return true;
}
});
}
uploadImage()
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
profilePicture.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
case 1:
if (resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
profilePicture.setBackgroundColor(Color.TRANSPARENT);
profilePicture.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
*Note: Case 0 is for image capturing using phones camera.
I can display it on my imageview but I need to store this in the phone's memory so everytime I will open the app, I will be able to load the previous uploaded image to the image view. Then if the user wants to upload again. The file previously saved will just be overwritten. I don't want to result to storing images as blob using sqlite since I will be uploading just one image for my whole app. I want to store it in a local file path like myappname/images/image.png. Any ideas? Thanks!
You can store an image in the application cache directory such as:
try {
String destFolder = getCacheDir().getAbsolutePath()+ "/images/";
if (!new File(destFolder).exists()) {
new File(destFolder).mkdirs();
}
FileOutputStream out = new FileOutputStream(destFolder + "profile.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
And read back the file into the Bitamp:
String fname = "profile.png";
Bitmap profile = BitmapFactory.decodeFile(getCacheDir().getAbsolutePath()+ "/images/" + fname);
I am able to open the gallery and getting the path of gallery as=
content://media/external/images/media/2
but not able to decode in imageview
this is my code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(Button) findViewById(R.id.Button01);
b.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_PICK);
}
});
}
//UPDATED
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath!=null)
{
path = selectedImageUri.toString();
m1.setPath(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap yourSelectedImage = BitmapFactory.decodeFile(path, options);
ImageButton img2=(ImageButton)findViewById(R.id.widget27);
img2.setImageBitmap(yourSelectedImage);
Toast.makeText(getBaseContext(), path, 1000).show();
}
}
}
}
public String getPath(Uri uri) {
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Please help thanks in advance
This piece of code should be put in your onActivityResult. It gives you the way to decode file path from fetched image URI:
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index_data);
Bitmap galleryImage = BitmapFactory.decodeFile(selectedImagePath);
We need to do following changes/fixes in our earlier onActivityResult()'s gallery picker code to run seamlessly on Kitkat and on all other earlier versions as well.
Uri selectedImgFileUri = data.getData();
if (selectedImgFileUri == null ) {
// user has not selected any photo
}
try {
InputStream input = mActivity.getContentResolver().openInputStream(selectedImgFileUri);
mSelectedPhotoBmp = BitmapFactory.decodeStream(input);
} catch (Throwable tr) {
// show message to try again
}