i am using the API21 SlidingTabLayout and SlidingTabStrips for my application.
I am saving an .tmp file of my intent camera photo. that works fine and i can see it on my phone package directory but i can store this .tmp file as .png ( i want to change the resolution because i need <1mb files instead of the 3mb files from the photo API intent)
i tried so many things in the last two hours and i can't solve it.
here is my code:
starting the intent with: takeAPicture
private void takeAPicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getView().getContext())));
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
the path of my .tmp file: getTempFile
private File getTempFile(Context context){
final File path = new File(Environment.getExternalStorageDirectory(), getView().getContext().getPackageName());
if(!path.exists()){
path.mkdir();
}
return new File(path, "test.tmp");
}
at least i handle the ActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult: Joined");
if(resultCode == Activity.RESULT_OK){
switch (requestCode){
case TAKE_PHOTO_CODE:
final File file = getTempFile(getView().getContext());
Toast.makeText(getActivity().getApplicationContext(), "Uri: " + Uri.fromFile(file), Toast.LENGTH_LONG);
try{
Bitmap captureBmp = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), Uri.fromFile(file));
FileOutputStream fos = new FileOutputStream(new File(new File(Environment.getExternalStorageDirectory(), getView().getContext().getPackageName()),"done.png"));
captureBmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
The fact is, the .tmp file is stored and the uri for
Bitmap captureBmp = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), Uri.fromFile(file));
is correct.
hope someone can help me
You can use my code:
public static boolean saveImage(Context context, byte[] image, String filename) {
Bitmap bitmapImage = BitmapFactory.decodeByteArray(image, 0, image.length);
return saveImage(context, bitmapImage, filename);
}
public static boolean saveImage(Context context, Bitmap image, String filename) {
try {
FileOutputStream fos = context.openFileOutput(filename,Context.MODE_PRIVATE);
imagem.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
File file = context.getFileStreamPath(filename);
} catch (Exception e) {
return false;
}
return true;
}
Related
I want to capture image and save it to specific folder in internal storage. Currently i am able to open intent and get thumbnail of captured image. I dont want to user extrnal stotage as now mostly users use their internal storage and not sd card.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent,1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
LayoutInflater inflater = LayoutInflater.from(LeaveApplicationCreate.this);
final View view = inflater.inflate(R.layout.item_image,attachView, false);
ImageView img = view.findViewById(R.id.img);
AppCompatImageView btnRemove = view.findViewById(R.id.btnRemove);
img.setImageBitmap(imageBitmap);
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attachView.removeView(view);
}
});
attachView.addView(view);
File directory = new File(Environment.getExternalStorageDirectory(),"/Digimkey/Camera/");
if (!directory.exists()) {
directory.mkdir();
}
File file = new File(directory, System.currentTimeMillis()+".jpg");
try (FileOutputStream out =new FileOutputStream(file)) {
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
First gain Write Permissions.
File directory = new File(Environment.getExternalStorageDirectory(), dirName);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, fileName);
if (!file.exists()) {
file.createNewFile();
}
try (FileOutputStream out =new FileOutputStream(file)) {
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
There are two types of storage.
1) Internal ex. "/root/.."
Unless you have rooted device, we can't access. this path.
2) External ex. "/storage/emuated/0"
Environment.getExternalStorageDirectory()
By using this path, we are able to create a directory/file.
Use to method to save your bimap in local storage. Pass bimap image as parameter i.e saveToInternalStorage(imageBitmap)
private String saveToInternalStorage(Bitmap bitmapImage){
//set image saved path
File storageDir = new File(Environment.getExternalStorageDirectory()
+ "MyApp"+ "/Files");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
File mypath=new File(storageDir,"bitmap_image.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Required permissions in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I want to take image from camera and store it and view it from internal storage.
I use this code to take image from camera.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PIC);
I tried the following to save the bitmap in internal storage.
public String saveToInternalSorage(Bitmap bitmapImage, String fileName){
File file = new File(createBasePath(), fileName + ".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getName();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PIC && resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/png");
startActivity(i);
}
}
My path is /data/user/0/com.dev/app/1454351400000/33352/capture_Image1.png
But here I am facing one issue. The bit map size is very small. I want exact image what I taken from camera.
Then I found one solution. Set the path before intent. So I tried like this.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
output = new File(createBasePath(), "capture_Image1" + ".png");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, TAKE_PIC);
When I use this code the image is not showing. on onActivityResult the resultCode showing -1.
If I use the following code
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.png");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, TAKE_PIC);
This code is working fine. After taking the image it showing image.
So please let me know store and retrieve the image from internal db with original quality.
Below is code to save the image to internal directory.
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Now Create imageDir
File mypath=new File(directory,"abc.jpg");
FileOutputStream foss = null;
try {
foss = new FileOutputStream(mypath);
// Using compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, foss);
} catch (Exception e) {
e.printStackTrace();
} finally {
foss.close();
}
return directory.getAbsolutePath();
}
Use below code for Reading a file from internal storage
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "abc.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
void openMultiSelectGallery() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri =getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
/* start activity for result pass intent as argument and request code */
startActivityForResult(intent, CAMERA_REQUEEST_CODE);
}
/**
* This method set the path for the captured image from camera for updating
* the profile pic
*/
private Uri getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "."
+ Constants.CONTAINER);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + System.currentTimeMillis() + ".png");
Uri uri = null;
if (mediaFile != null) {
uri = Uri.fromFile(mediaFile);
}
return uri;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK
&& requestCode == CAMERA_REQUEEST_CODE) {
String path =fileUri.getPath();
//decode the path to bitmap here
}
}
After image was download, I save it in an internal storage at
Android/data/%packagename%/cache directory. below is a code.
private class SaveImageToStorage extends AsyncTask<Void,Void,Void>
{
String picName;
Bitmap bitmap;
public SaveImageToStorage(String name, Bitmap bitmap)
{
this.picName = name;
this.bitmap = bitmap;
}
#Override
protected Void doInBackground(Void... params) {
if(bitmap != null && !picName.isEmpty()) {
File file = new File(feedImagesCacheDir.getPath(), extractImageNameFromUrl(picName));
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.WEBP, 80, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
And after all of this I just want to open the image in android gallery.
I try below code and it doesn't work.It show me Toast "can't find the image".
So I've tried remove "file://", then it open gallery with nothing but something like broken image icon.
private void openImageInGallery(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://"+getFeedImagesCacheDir().getPath() + "/" + imgName+".webp"), "image/*");
startActivity(intent);
}
I think that maybe I save it in cache folder, so its became private with only access to my app.
How can I fix this?
Thanks.Sorry for my bad ENG.
Cache Image are not view directly because is save like encrypted format so first you download that image and save into SD card. use below code.
String root = Environment.getExternalStorageDirectory().toString();
String wallpaperFilePath=Android/data/%packagename%/cache/imagename;
File cacheDir = GlobalClass.instance().getCacheFolder(this);
File cacheFile = new File(cacheDir, wallpaperFilePath);
InputStream fileInputStream = new FileInputStream(cacheFile);
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = scale;
bitmapOptions.inJustDecodeBounds = false;
Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
File myDir = new File(root + "/saved_images");
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);
wallpaperBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
By using this line you can able to see saved images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
You can download images into DCIM (your gallery folder in sdCard).
Then use below to open gallery:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Hope this help!
I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly
I have captured image through camera intent and image are saved to internal memory.But my images are also stored in gallary .I don't want to save the images into gallary for private purpose.
Here is my code:-
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);#SuppressLint("NewApi")
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
FileOutputStream mFileOutStream1;
try {
mFileOutStream1 = openFileOutput("IMG" + counter + ".png", Context.MODE_PRIVATE);
photo.compress(CompressFormat.JPEG, 100, mFileOutStream1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this code
private String saveToInternalSorage(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,"profile.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.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
Hope this help you..!!!