Save a bitmap as image in Genymotion - android

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

Related

how to select a picture form local album in android

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));

How do I save image in imageview?

My app lets you pick an image from gallery and shows it in imageview, but when you close the activity and open it again the image is not there anymore.
private final static int RESULT_LOAD_IMAGE = 1;
public void getpic(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == 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]);
String selectedimage = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageButton3);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageBitmap(BitmapFactory.decodeFile(selectedimage));
}
}
How can I save the picked image?
You can get Bitmap from ImageView to save it:
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
Use Glide for loading image
add below dependencies in build.gradle(app)
compile 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'
add below code inside your onActivityResult
Glide
.with(mContext)
.load(selectedimage)
.centerCrop()
.placeholder(R.color.black)
.crossFade()
.into(imageView);
For more details refer
https://github.com/bumptech/glide
http://en.proft.me/2016/09/12/load-process-and-cache-image-android-using-glide/
Glide load local image by Uri.

Not able to copy image using ACTION_GET_CONTENT

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();
}
}

Camera Intent returns no file path

I have a problem with my camera Intent. It saves the pictures to the storage, but it doesn't return the file path to my activity. When i remove the EXTRA_OUTPUT it returns the file path, but then the images have just a very small size. Is there any solution to get the pictures with original size without using EXTRA_OUTPUT?
Here is my code:
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
preinsertedUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, preinsertedUri);
startActivityForResult(intent, OPEN_CAMERA);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case OPEN_CAMERA:
if (resultCode == RESULT_OK && data != null) {
Uri imageUri = null;
imageUri = data.getData();
if(imageUri == null && preinsertedUri != null){
imageUri = preinsertedUri;
}
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filePath = cursor.getString(columnIndex);
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(filePath);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Try this it might help you.
When I capture the photo from camera so I implement a logic using Cursor and iterate the cursor and get the last photo path which is capture from camera.
It give the path of last capture photo from camera.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}

Low picture/image quality when capture from camera

I have one problem. When I try to get picture from camera, the quality is very low.
At first, capture the picture using camera, than save to the directory and at the same time get that picture and show in my app.The picture saved inside directory is a fine quality but when I get it from directory, the quality is low. below is my sample code :
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) intent.getExtras().get("data");
if (g==1)
{
ImageView myImage = (ImageView) findViewById(R.id.img5);
myImage.setImageBitmap(thumbnail);
View a = findViewById(R.id.img5);
a.setVisibility(View.VISIBLE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray1 = stream.toByteArray();
}
}
any solution/suggestion?
Thanks :)
Solved
The problem solved when I follow the code given by Antrromet below
I have used the following code and this works perfectly fine for me.
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
and also
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I will give you something that work for me. I asked the same !
Solution to save a picture in a specific folder without lost quality
I FOUND THE SOLUTION:
//Create a new folder code:
String path = String.valueOf(Environment.getExternalStorageDirectory()) + "/your_name_folder";
try {
File ruta_sd = new File(path);
File folder = new File(ruta_sd.getAbsolutePath(), nameFol);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(MainActivity.this, "Carpeta Creada...", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
Log.e("Carpetas", "Error al crear Carpeta a tarjeta SD");
}
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
finish();//agregue este
//Method to take a Picture
public void clickFoto(View view) {
takePic();
}
//takePic()
private void takePic() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
*File file = new File(Environment.getExternalStorageDirectory(), "/your_name_folder/a" + "/photo_" + timeStamp + ".png");*
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
}
//onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgFoto.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// getRealPathFromUri
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);
}
Add the photo to a gallery
.
.
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
for more detail : https://developer.android.com/training/camera/photobasics.html

Categories

Resources