I've been trying different things and I can save a photo in the SD card taken with Camera (not intent) but cannot pick up this same picture from SD card and place it in an ImageView. I get a Null pointer Exception allways.
Don't know what's missing, hope somebody can help me:
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Save the image JPEG data to the SD card
FileOutputStream fos = null;
String fileName = "";
try {
fileName = "/mnt/sdcard/DCIM/MyPicture.jpg";
fos = new FileOutputStream(fileName);
fos.write(data);
fos.close();
Toast.makeText(getBaseContext(), "Image saved:" ,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Log.e(TAG, "File Note Found", e);
Toast.makeText(getBaseContext(), "Image couldn't be saved.",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
Toast.makeText(getBaseContext(), "Image couldn't be saved.",
Toast.LENGTH_LONG).show();
}
Bitmap bitmap = BitmapFactory.decodeFile(fileName);
Log.d(TAG, fileName);
mImageView.setImageBitmap(bitmap);
}
};
I have tried that too:
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
+ "/DCIM/MyPhoto.jpg");
mImageView.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
It saves the picture but goes to the catch when trying to put the image in the ImageView saying that "Error reading file"
logcat:
DDMS:
Sorry everybody for the headache... I forgot to put mImageView = (Imageview)findViewById(R.id.imageView1);
I'm a disaster :-)
Try this,
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
Log.v("Path", Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
mImageView.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
also check your imageview mImageView initialized or not
Use this. It would help you.
public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(CameraPhotoCapture.this);
Bitmap mBitmap;
protected void onPreExecute() {
/****** NOTE: You can call UI Element here. *****/
//UI Element
Dialog.setMessage("Loading image from Sdcard..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
try {
/** Uri.withAppendedPath Method Description
* Parameters
* baseUri Uri to append path segment to
* pathSegment encoded path segment to append
* Returns
* a new Uri based on baseUri with the given segment appended to the path
*/
uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + urls[0]);
/************** Decode an input stream into a bitmap. *********/
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
/********* Creates a new bitmap, scaled from an existing bitmap. ***********/
newBitmap = Bitmap.createScaledBitmap(bitmap, 170, 170, true);
bitmap.recycle();
if (newBitmap != null) {
mBitmap = newBitmap;
}
}
} catch (IOException e) {
//Error fetching image, try to recover
/********* Cancel execution of this task. **********/
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if(mBitmap != null)
showImg.setImageBitmap(mBitmap);
}
}
Related
Good morning,
I have following code to download bitmpa from server
/*SAVE IMAGE++++++++++++++++++++*/
public void saveImage(Context context, Bitmap b, String imageName) {
FileOutputStream foStream;
try {
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 100, foStream);
foStream.close();
UPDTV_FOTO.setBackgroundColor(Color.GREEN);
image.setImageBitmap(loadImageBitmap(getApplicationContext(), Giocatore));
UPDTV_FOTO.setText("Download "+Giocatore+ " Complete");
}
catch (FileNotFoundException e) {
Log.d("saveImage", "file not found");
e.printStackTrace();
// UPDTV_FOTO.setText("FILE NOT FOUND");
}
catch (IOException e) {
Log.d("saveImage", "io exception");
e.printStackTrace();
// UPDTV_FOTO.setText("SAVE IMAGE ERROR");
}
}
/*SAVE IMAGE+++++++++++++++++++++++++*/
/*DOWNLOAD IMAGE++++++++++++++++++++++*/
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception 1, Something went wrong!");
e.printStackTrace();
// UPDTV_FOTO.setText("DOWNLOAD ERROR");
}
return bitmap;
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
protected void onPostExecute(Bitmap result) {
saveImage(getApplicationContext(), result, Giocatore);
}
}
/*DOWNLOAD IMAGE++++++++++++++++++++++*/
/*LOAD IMAGE*+++++++++++++++++++++++++++++++++++++*/
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream = context.openFileInput(imageName);
bitmap = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception 3, Something went wrong!");
e.printStackTrace();
// UPDTV_FOTO.setText("LOAD ERROR");
}
return bitmap;
}
/*LOAD IMAGE+++++++++++++++++++++++++++*/
if the bitmap I try to download is available on server all works fine with
new DownloadImage().execute(myurl);
else if is not available, my app crashes.
So I would like to check if bitmap is available on servere before starting download.
I try
if (URLUtil.isValidUrl(URL+FotoGiocatore)==true);
and also
How can I programmatically test an HTTP connection?
Check if file exists on remote server using its URL
You can also use below code to check if the image is present
URL url = new URL("YOUR URL");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
`int status = urlConnection.getResponseCode();`
and only start download if status==200
I use this code to download an Image
public void buttonCondivisione(View view) {
//onShareItem(view);
String url = Utilities.removeString(mImages[POSITION_IMAGE].getLink());
new DownloadImage().execute(url);
}
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception 1, Something went wrong!");
e.printStackTrace();
}
return bitmap;
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
protected void onPostExecute(Bitmap result) {
saveImage(getApplicationContext(), result, "my_image.png");
}
}
public void saveImage(Context context, Bitmap b, String imageName) {
FileOutputStream foStream;
try {
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
foStream.close();
Toast.makeText(CategoryActivity.this, "FATTO", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("6SENSE_APP Save Image", "Exception 2, Something went wrong!");
Toast.makeText(CategoryActivity.this, "No FATTO", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
But i can't find the image after the download. It's all ok because i see the Toast message after few seconds. I try different way to download my images but every method don't work for me. Stackoverflow is my last chance.
How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary.
I need to:
If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps
P.S. Sorry me, I can make some mistakes in question because I don`t very good know English.
This my class:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
Try to use this code:
Method for loading image from imageUrl
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
I had this same issue and I hope this helps. First, To download Image from URL into your app, use the code below:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
In order for the image to be displayed inside the app, use the method below in your onCreate method:
new DownloadImageTask((ImageView) -your imageview id-)
.execute(-your URL-);
In order for the image to be saved INTERNALLY inside the app/phone, use the code below:
#SuppressLint("WrongThread")
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bmImage.setImageBitmap(result);
}
}
To load the image from the internal storage, use the code below:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "image.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Things to note: 1. path is the a string containing the path of the file. 2. "image.jpg" is the file name so ensure that matches with yours. 3. "MyImages" is a folder in your path which contains the actual saved image.
can someone help me?
I want to take a screenshot and post this to the facebook wall (with a message)!
I have read several topics and forums but i dont find something that worked for me!
I already have the facebook SDK!
Thanks a lot!
capture images of view using this way.
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "yourImageName.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here v is root layout and than post photo in facebook using SDK 3.5.
like this way
private SimpleFacebook mSimpleFacebook;
mSimpleFacebook = SimpleFacebook.getInstance(this);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
// create Photo instace and add some properties
Photo photo = new Photo(bitmap);
photo.addDescription("Screenshot from sample application");
photo.addPlace("110619208966868");
// publish
mSimpleFacebook.publish(photo, new OnPublishListener()
{
#Override
public void onFail(String reason)
{
mProgress.hide();
// insure that you are logged in before publishing
Log.w(TAG, "Failed to publish");
}
#Override
public void onException(Throwable throwable)
{
mProgress.hide();
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while publishing
mProgress = ProgressDialog.show(this, "Thinking",
"Waiting for Facebook", true);
}
#Override
public void onComplete(String id)
{
mProgress.hide();
toast("Published successfully. The new image id = " + id);
}
});
So I've been looking around for an explanation on how to download a URL image (.png) to the phone itself-
I have a method going off on a menu select once they choose the photo- and it sends over the URL path as well as the filename i would like it to be called(test.png for the time being)
I am trying to do this AsynC as well to keep the UI free-
The code below actually goes off fine, but it doesn't seem to save any image though-
(I don't have an SD card on my phone, but I tried saving to the data folder for testing as well, with same results)
protected void saveImage(String imageUrl, String fileName){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
private String imageUrl;
private String fileName;
public SendPostReqAsyncTask (String imageUrl, String fileName)
{
super();
this.imageUrl=imageUrl;
this.fileName=fileName;
}
#Override
protected String doInBackground(String... params) {
String newfilename="";
try {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
URL urlTmp = new URL(imageUrl);
newfilename = urlTmp.getFile();
newfilename = externalStorageDirectory + "/" + fileName;
Bitmap bitmap = BitmapFactory.decodeStream(urlTmp.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(newfilename);
if (bitmap != null) {
bitmap.compress(CompressFormat.PNG, 50, fileOutputStream);
return newfilename;
}
} catch (MalformedURLException e) {
Log.w("errorSaving", "Could not save image with url: " + imageUrl, e);
} catch (IOException e) {
Log.w("errorSaving", "Could not save image with url: " + imageUrl, e);
}
Log.d("errorSaving", "Failed to save image " + fileName);
return newfilename;
}
//handle result when done
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "Photo saved to phone: " + result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(imageUrl,fileName);
sendPostReqAsyncTask.execute();
}
//To download image from a url
Drawable image;
try {
InputStream is = (InputStream) this.fetch(your_image_url);
image = Drawable.createFromStream(is,"src");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Convert drawable to Bitmap
Bitmap bitmap = ((BitmapDrawable)image).getBitmap();
//Save Bitmap to a file
try {image
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
Also make sure that you set the internet permission in manifest file,
<uses-permission android:name="android.permission.INTERNET" />