How to read an image from internal storage - android

I have downloaded an image to my app data/data/package memory. it is downloaded, but problem is that i did not got path to display image in imageviewer. but could not. please tell me how to display. Please attention on path. thank you
Here is my download code.
ImageView imageView = (ImageView) findViewById(R.id.iv);
String mUrl = "https://cometonice.com/im.gif";
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
FileOutputStream outputStream;
String name = "im.gif";
outputStream = openFileOutput(name, Context.MODE_PRIVATE);
outputStream.write(response);
outputStream.close();
Toast.makeText(MainActivity.this, "Download complete.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);

Well you can use The ImageRequest of volley like this :
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
saveBitmapToFile(bitmap)
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
});
and save it like :
public String saveBitmapToFile(Bitmap bitmap) {
FileOutputStream out = null;
String filename = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "myapp");
if (!f.exists()) {
f.mkdirs();
}
filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp/" + UUID.randomUUID().toString() + ".jpg";
out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return filename;
}

Related

how can i change bitmap saving location

How can change image saving location i have created the folder but how to save image in it. all downloaded images are saved in pictures folder
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
file = new File(Environment.getExternalStorageDirectory().getPath() + "/CreativeGraphy");
if (!file.exists()) {
file.mkdir();
}
try {
file.createNewFile();
MediaStore.Images.Media.insertImage(r, bitmap, name, desc);
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
Toast.makeText(context, "Download succeed ", Toast.LENGTH_SHORT).show();
}
Use this method
public static void saveBitmap(String path, Bitmap bitmap) {
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
After saving you can call scanFile method to index your file in the gallery.
MediaScannerConnection.scanFile(context, new String[]{path}, null, null);
thanks everyone This works
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CreativeGraphy";
File dir = new File(file_path);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir,name );
FileOutputStream fOut;
try {
MediaStore.Images.Media.insertImage(r, bitmap, name, desc);
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
Toast.makeText(context, "Download succeed ", Toast.LENGTH_SHORT).show();
}

Unable to save image from Json response using Volley

Save Image from ImageView in android Not Working. Image loading By Volley from JSON . I want to save that image in Gallery but on some devices this code not working.
BitmapDrawable draw = (BitmapDrawable) thumbnail.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File dir = new File(Environment.getExternalStorageDirectory() + "");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(JobsDetail.this, "Download Successfully", Toas.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);
Simply use this to download directly from Image Url
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
progressBar.setVisibility(View.GONE);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
LicenseFrontFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Set the bitmap into ImageView
//image.setImageBitmap(result);
// Close progressdialog
}
To use , call this way
new DownloadImage().execute(image_url);
Add write permissions in manifest also
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And runtime persmissions for Marshmallow or above devices
Create a class SaveImageHelper code is below
public class SaveImageHelper implements Target {
private Context context;
private WeakReference<AlertDialog> mDialog;
private WeakReference<ContentResolver> contentResolverWeakReference;
private String name;
private String desc;
public SaveImageHelper(Context context,AlertDialog alertDialog, ContentResolver contentResolver, String name, String desc) {
this.context = context;
this.mDialog = new WeakReference<AlertDialog>(alertDialog);
this.contentResolverWeakReference = new WeakReference<ContentResolver>(contentResolver);
this.name = name;
this.desc = desc;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog dialog = mDialog.get();
if(r != null)
MediaStore.Images.Media.insertImage(r,bitmap,name,desc);
dialog.dismiss();
Toast.makeText(context, "Image Download Successfully...", Toast.LENGTH_SHORT).show();
//Open Gallery After Download
//Intent intent = new Intent();
//intent.setType("image/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
// context.startActivity(Intent.createChooser(intent,"SELECT PICTURE"));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
and Use it in another class / Activity by button click
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ActivityCompat.checkSelfPermission(JobsDetail.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(JobsDetail.this, "You Should Grant Permission..", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}
return;
}
else{
AlertDialog dialog = new SpotsDialog(JobsDetail.this);
dialog.show();
dialog.setMessage("Downloading....");
String filename = UUID.randomUUID().toString()+".jpg";
Picasso.with(getBaseContext())
.load(imageUrl)
.into(new SaveImageHelper(getBaseContext(),
dialog, getApplicationContext().getContentResolver(),
filename,"Image Descp"));
}
Also set Permission in oncreate to access files and images in device
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}

Not able to upload camera captured image on server in android

I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.
// code for the same
// code fro open camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
// on activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA) {
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");
Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));
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();
}
filePath = destination.toString();
if (filePath != null) {
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
}
}
// send to server code
private void execMultipartPost() throws Exception {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
Log.d("TAG", "file new path: " + file.getPath());
Log.d("TAG", "contentType: " + contentType);
RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);
final String filename = "file_" + System.currentTimeMillis() / 1000L;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("date", "21-09-2017")
.addFormDataPart("time", "11.56")
.addFormDataPart("description", "hello")
.addFormDataPart("image", filename + ".jpg", fileBody)
.build();
Log.d("TAG", "execMultipartPost: "+requestBody);
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://myexample/api/user/lets_send")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.d("TAG", "response of image: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
// I am getting onFailure executed while try to upload image from camera.
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
As per comments :
Get image from gallery or camera like this :
File mainFile = null;
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
String partFilename = currentDateFormat();
mainFile = storeCameraPhotoInSDCard(bitmap, partFilename);
public String currentDateFormat() {
String currentTimeStamp = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
currentTimeStamp = dateFormat.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
return currentTimeStamp;
}
public File storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate) {
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outputFile;
}
Use mainFile to send in RequestBody and pass like execMultipartPost(File file)

Just go to the target once and it should go 4 times. Picasso/Target

So I implement picasso, so I can download images and save them on sd cart, so when I want i can use them on the program.
I have a for loop:
for (int i = 0; i < listaProdutos.size(); i++) {
caminho =listaProdutos.get(i).getImagem();
Picasso.with(getApplicationContext()).load("URL"+listaProdutos.get(i).getImagem()).into(target);
}
But I just get into target once and its the last one of for loop,
target code:
private Target target = new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
//new Thread(new Runnable() {
//#Override
//public void run() {
/*
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(),caminho);
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
try {
verifyStoragePermissions(AtividadePrincipal.this);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/imagensDaApp");
myDir = new File(myDir, caminho);
if (!myDir.exists()) {
myDir.getParentFile().mkdirs();
//myDir.createNewFile();
}
FileOutputStream out = null;
out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//}
//}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {
}
}
};
I commented the thread because it does the same thing with or without, if you want you cant uncomment.
I have alredy search about it, but i couldnt find any answer for this problem, all the URL are ok!
I have been been doing this for 3 days, and it keep the same.
YES listaProdutos.size() = 4;
AND all the url are ok!
If u didnt understand the question, please say.
Why not use the following code? No Targets are used here, so no target is getting gc'ed
I took the freedom to optimize your code a little as well. I've done this without testing the code, but it should work without any problems.
new Thread(new Runnable(){
#Override
public void run(){
for (int i = 0; i < listaProdutos.size(); i++) {
caminho =listaProdutos.get(i).getImagem();
try {
verifyStoragePermissions(AtividadePrincipal.this);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/imagensDaApp");
myDir = new File(myDir, caminho);
if (!myDir.exists()) {
if(myDir.getParentFile().mkdirs()){
//myDir.createNewFile();
FileOutputStream out = null;
out = new FileOutputStream(myDir);
Picasso.with(getApplicationContext()).load("URL"+listaProdutos.get(i).getImagem()).get().compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
}catch{IOException e) {
e.printStackTrace();
}
}
}
}).start();
You can create a class implementingTarget:
class MyTarget implements Target {
String name;
public MyTarget(String name) {
this.name = name;
}
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
//new Thread(new Runnable() {
//#Override
//public void run() {
/*
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(),caminho);
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
try {
verifyStoragePermissions(AtividadePrincipal.this);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/imagensDaApp");
myDir = new File(myDir, name);
if (!myDir.exists()) {
myDir.getParentFile().mkdirs();
//myDir.createNewFile();
}
FileOutputStream out = null;
out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//}
//}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {
}
}
};
And use it inside the cycle:
for (int i = 0; i < listaProdutos.size(); i++) {
caminho =listaProdutos.get(i).getImagem();
Picasso.with(getApplicationContext()).load("URL"+listaProdutos.get(i).getImagem()).into(new MyTarget(caminho ));
}

android-how to save a view to sd card

i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}

Categories

Resources