Android: Saving image to storage - java

Currently my application, takes a photo, and put's the data into a ImageView.
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
Now, i want it to do this: When the user clicks the button 'Save Button' I would like it to save to storage. How would i do this? I have my button set up with an OnClick listener.
public void save_btn() {
}

Step #1: Hold onto the Bitmap somewhere
Step #2: When the button is clicked, fork a background thread, AsyncTask, IntentService, etc. to do the work
Step #3: In the background thread (or whatever), call compress() on the Bitmap, providing an OutputStream on whatever file you want to write to

use Bitmap compress method to store bitmap into the android data storage. and if you want to store full size of image then please use intent.putExtra with file uri or even you can create your own content Provider (Which is my fav).
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
http://developer.android.com/training/camera/photobasics.html#TaskPath
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));

Try this:
String filename = "somename.jpg"; // your filename with path to sdcard
File file = new File(filename);
OutputStream outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); // your bitmap
outStream.flush();
outStream.close();

Using the code you can save image on sd card :
FileOutputStream outStream = null;
File f=new File(Environment.getExternalStorageDirectory()+"/My Image/");
f.mkdir();
String extStorageDirectory = f.toString();
File file = new File(extStorageDirectory, "image.jpg");
pathOfImage = file.getAbsolutePath();
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
try {
outStream.flush();
outStream.close();
} catch (IOException e) {e.printStackTrace();}

Related

How to share Screenshot of current page by using intent?

I am developing and android blog application where I want to share my current blog page screenshot.I try but it showing file format is not supported..please help me to find my error..Thanks in advance
MyAdapter.java
sendImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap app_snap = ((BitmapDrawable)movie_image.getDrawable()).getBitmap();
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SaveImg";
System.out.println("****FILEPATH **** : " + file_path);
File imagePath = new File(Environment.getExternalStorageDirectory() + "/scr.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
System.out.println("****FILEPATH1 **** : " + file_path);
app_snap.compress(Bitmap.CompressFormat.PNG, 200, fos);
System.out.println("****FILEPATH2 **** : " + file_path);
fos.flush();
fos.close();
}
catch (IOException e) {
System.out.println("GREC****** "+ e.getMessage());
}
Intent sharingIntent = new Intent();
Uri imageUri = Uri.parse(imagePath.getAbsolutePath());
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
context.startActivity(sharingIntent);
}
});
Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:
First, you need to add a proper permission to save the file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
If you want to use this on fragment view then use:
View v1 = getActivity().getWindow().getDecorView().getRootView();
instead of
View v1 = getWindow().getDecorView().getRootView();
on takeScreenshot() function
Note:
This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:
Android Take Screenshot of Surface View Shows Black Screen
if u have any doubt please go through this link
You can get the Bitmap of your screen view inside your layouts. Where view will be your layout views like Linear or RelativeLayout
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap returnedBitmap = view.getDrawingCache();
then have to convert into byte[] so that you can send with the Intent like this following:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
and send data with Intent like this:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("bitmap_",byteArray);
get Intent on your SecondActivity like this:
byte[] byteArray = getIntent().getByteArrayExtra("bitmap_");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

Reduce image file size from camera crop

I am trying to implement the best approach to reduce a file, basicly my app is about plants, i need high quality images, so the first thing i did was use a external library to crop images in thumbnail(so i can mantain aspect ratio) i use 1:1 thumnbnail format.
Every time i take a picture and if everything is ok on activityResult, it calls the builded crop library so i can cut and get the uri, like this:
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
dateTimer = getTime();
Log.d("codig",String.valueOf(requestCode));
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Log.d("resultOK","resultOK");
CropImage.activity(data.getData())
.setAspectRatio(1,1)
.setInitialCropWindowPaddingRatio(0)
.setActivityTitle("Corte a foto")
.setActivityMenuIconColor(R.color.nephritis)
.setRequestedSize(300, 300, CropImageView.RequestSizeOptions.RESIZE_INSIDE)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri uri = result.getUri();
Bitmap pic = null;
try {
pic = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
path = saveToInternalStorage(pic);
Log.d("caminho",path);
showDetailsDialog(data);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Log.d("pict12",error.toString());
}
}
}
as you guys can see i have a setRequestSize method there, where i reduce the size of the image (this works, but just sometimes, the text i send as base64 is still to big.
i convert the uri to bitmap and save it on the device file, on next acitivty i get the file
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"captured.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
so on next activity i get it like this:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "captured.jpg");
Log.d("filehe",f.toString());
b = BitmapFactory.decodeStream(new FileInputStream(f));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
i get the b(bitmap) and covert him to byte[] after to base64(what my server asks for)
byte[] capture = encodeImage(b);
String encodedImage = Base64.encodeToString(capture,1);
Log.d("encodedImage",encodedImage);
params.put("base64", encodedImage);
the problem here is that i need to preserve the quality of the image and i can't get the quality without increasing the heavyness on my server, can't i compress it somehow? i do it on the file but doesn't work

Not getting correct Path when Select Image from Gallery

When I take an image by Camera, its works fine and I get the image path to save in SQLite database and can retrieve the path to show required image. But when I select an image from Gallery I don't get the correct path which I need to save in database for the further retrieve. I don't get image cause the path is incorrect when I save path in the database. So my question is - how can I get the correct absolute path of the gallery image?
#RequiresApi(api = Build.VERSION_CODES.N)
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");
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();
}
Bitmap bm = BitmapFactory.decodeFile(destination.getAbsolutePath());
ivImage.setImageBitmap(bm);
showImagepathET.setText(destination.getAbsolutePath());// This path will save in database
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
showImagepathET.setText(destination.getAbsolutePath());// This path will save in database
ivImage.setImageBitmap(bm);
}
Here, I get the correct image to show in ImageView ivImage in both take an image by camera or gallery. But I don't get the path correctly when I pick an image from Gallery(works fine when I take camera Image) which I save in database for further path retrieve.
how i can get this selected image path
For what feels like the 3,735th time, there is no "selected image path". You are getting a Uri back (data.getData()); a Uri does not have to point to a file. For example, http://stackoverflow.com/questions/44057912/not-getting-correct-path-when-select-image-from-gallery is a Uri; it does not represent a file on the filesystem.
If you want a file, use a file-picker library.
At last, I decided to do the same procedure what I did in Method "onCaptureImageResult(Intent data)". The image I get from the Gallery stored again to a directory.I know this is absolutely not the good procedure, but it solved my problem temporally until I get a good answer.
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
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();
}
Bitmap bm1 = BitmapFactory.decodeFile(destination.getAbsolutePath());
ivImage.setImageBitmap(bm1);
String selectedImageUri = data.getData().getPath();
showImagepathET.setText(destination.getAbsolutePath());
}

sharing images from drawable

i'm trying to send images from my app, but it only sends one image (the one mentioned in the code below image_intro.
i want the app to share whatever image the user chooses.
Here is the code i used:
// Share event start
final Button share = (Button) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.image_intro);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/LatestShare.jpg";
OutputStream out = null;
File file=new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path=file.getPath();
Uri bmpUri = Uri.parse("file://"+path);
Intent shareIntent = new Intent();
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/jpg");
startActivity(Intent.createChooser(shareIntent,"Share with"));
}
});
im counting in your help friends, thanks
i managed to solve it by adding these two lines:
ImageView image = (ImageView) findViewById(R.id.ba‌​ckgroundPreview);
Bitmap bitmap = ((BitmapDrawable)ima‌​ge.getDrawable()).get‌​Bitmap();

Save an image from the gallery of an Android Phone to Parse - Can't save .jpg photos

After following part of this tutorial and the second answer of this question in SO, I managed to save a photo that I chose from my gallery to my object in Parse.
The problem is that the photo that I saved has .PNG extension (it was just a screenshot).
When I tried to choose a normal photo from the camera folder, nothing was saved and an exception was occurred.
The extension of ALL the other photos is .jpg NOT .jpeg.
Because of that, i tried to put if statements, so that I can check the type of the photo.
The result of the code that is following is that when I choose a .JPG photo, the data type is NULL.
But, how can I manage to save the .jpg photos in my Parse Object ?
In my Activity I have 2 buttons. when you press the first one ( sign_in ), there is the listener that does correctly all the checks of the other data in my page and then if all data are okay, it calls a function ( postData() ), in which there will be done the saving to parse via objects.
The second button is about adding a photo from gallery. In my .java activity, I have this exact listener:
picture.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
}
});
This is the function that it is being called from the onClick function of the button:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Detects request codes
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
selectedImageType =data.getType();
Toast.makeText(SignUpActivity.this, "Type: "+selectedImageType,
Toast.LENGTH_SHORT).show();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
if (selectedImageType == "JPEG"){
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
image = stream.toByteArray();
}
else if (selectedImageType == "JPG" || selectedImageType == "jpg"){
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
image = stream.toByteArray();
}
else if (selectedImageType == "PNG") {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
image = stream.toByteArray();
}
else{
Toast.makeText(SignUpActivity.this, "Please pick a JPEG or PNG photo!",
Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And this is the function that saves the data:
public void postData(final String username,final String password,final String email,final String gender,final String age) {
ParseObject user = new ParseObject("users");
user.put("username", username);
user.put("password", password);
user.put("email", email);
user.put("gender", gender);
user.put("age_category", age);
user.put("admin", false);
ParseFile file = null;
if (selectedImageType == "JPEG"){
file = new ParseFile("profile_picture.jpeg", image);
}
else if (selectedImageType == "JPG" || selectedImageType == "jpg"){
file = new ParseFile("profile_picture.jpg", image);
}
else if (selectedImageType == "PNG"){
file = new ParseFile("profile_picture.png", image);
}
else{
// Show a simple toast message
Toast.makeText(SignUpActivity.this, "Please pick a JPEG or PNG photo!",
Toast.LENGTH_SHORT).show();
}
// Upload the image into Parse Cloud
file.saveInBackground();
user.put("photo", file);
// Create the class and the columns
user.saveInBackground();
// Show a simple toast message
Toast.makeText(SignUpActivity.this, "Image Uploaded",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
//finish();
}
remove your if statements that try to keep track of the "selectedImageType" throughout the process of bitmap creation and image Post to parse.com.
Once you have a bitmap, you can simply specify all compression to "Bitmap.CompressFormat.JPEG" and then simply post all jpgs to parse.com.
So .jpeg works and .jpg doesn't? How about this then (notice you shouldn't compare strings with ==):
if (selectedImageType.toUpperCase().equals("JPEG") || selectedImageType.toUpperCase().equals("JPG")){
file = new ParseFile("profile_picture.jpeg", image);
}
Also you can consolidate some earlier code:
if (selectedImageType.toUpperCase().equals("JPEG") || selectedImageType.toUpperCase().equals("JPG")){
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
image = stream.toByteArray();
}

Categories

Resources