Hi i have downloaded a image from a URL and written it as a bitmap to a file. I'm trying to retrieve the bitmap from the file and display it. Does anyone know how to do this? heres what i have tried it doesn't error but it doesn't display the image.
Global.java
public static void saveBitmapToFile(Context activityContext, Bitmap bitmap, String FileName){
try{
File file = new File(FileName);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();}
catch (Exception e) {
e.printStackTrace();
Log.i(null, "Save file error!");
}
}
public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
Bitmap bitmap = BitmapFactory.decodeFile(FileName);
return bitmap;
}
GetBitmap.java
public void downloadUserPhoto(){
String userPhotoUrl = "http://static.bbci.co.uk/h4discoveryzone/ic/newsimg/media/images/229/129/68805000/jpg/_68805145_pahs2.jpg"
userPhoto = Global.createBitmapFromUrl(this, userPhotoUrl);
Global.saveBitmapToFile(this, userPhoto, "user_photo");
}
public void getUserPhoto(){
loadingText.setText("Getting User Pictures...");
Bitmap setUserPhoto = Global.returnBitmapFromFile(this, "user_photo");
logo.setImageBitmap(setUserPhoto);
}
Try to open it by using FileInputStream:
public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
FileInputStream in = new FileInputStream(FileName);
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA= new byte[buf.available()];
buf.read(bitMapA);
buf.close();
in.close();
Bitmap bitmap = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
return bitmap;
}
Other way is to use openFileInput:
public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
FileInputStream fis;
try {
fis = openFileInput(FileName);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
fis.close();
return bitmap;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Related
The pixels values changed after write and read the image.
we save(both txt file and jpg) the image which come from camera by the following:
SaveToTXTFile(bytesArrayFromCamera, pathToTxtFile);
mOriginalImage = ByteArrayToBitmap(bytesArrayFromCamera);
SaveToJPGFile(mOriginalImage, pathToOcrJPG);
public static boolean SaveToTXTFile(byte[] image, String fileFullName){
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileFullName));
bos.write(image);
bos.flush();
bos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
public static Bitmap ByteArrayToBitmap(byte[] bytes){
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inMutable = true;
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = null;
try{
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, bitmapOptions);
}
catch (Exception e)
{
e.printStackTrace();
}
return bitmap;
}
public static boolean SaveToJPGFile(Bitmap bmp, String path){
FileOutputStream out = null;
try {
File file = new File(path);
if(file.exists()){
file.delete();
}
File folder = new File(file.getParent());
if(!folder.exists())
{
Boolean isSuccess = folder.mkdirs();
if(!isSuccess)
throw new Exception("Can't create directory(ies)");
}
out = new FileOutputStream(path);
// bmp is your Bitmap instance, PNG is a lossless format, the compression factor (100) is ignored
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
Then we read the txt file, convert it to mat and then to bitmap and save as jpg file:
mat = GetBillMat(pathToTxtFile);
SaveMatToJPGFile(mat, pathToOcr1JPG);
public static Mat GetBillMat(String billFullName) throws IOException {
byte[] bytes = ImageTxtFile2ByteArray(billFullName);
Mat mat = BytesToMat(bytes);
return mat;
}
public static byte[] ImageTxtFile2ByteArray(String path) throws IOException {
File file = new File(path);
int size = (int) file.length();
byte[] image = new byte[size];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
bis.read(image);
bis.close();
return image;
}
public static Mat BytesToMat(byte[] bytes) {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
}
Mat jpegData = new Mat(1, bytes.length, CvType.CV_8UC1);
jpegData.put(0, 0, bytes);
Mat bgrMat = new Mat();
Mat dstMat = new Mat();
bgrMat = Imgcodecs.imdecode(jpegData, Imgcodecs.IMREAD_COLOR);
Imgproc.cvtColor(bgrMat, dstMat, Imgproc.COLOR_BGR2RGBA, 4);
return dstMat;
}
public static boolean SaveMatToJPGFile(Mat mat, String path){
Bitmap bmp = Bitmap.createBitmap(mat.width(), mat.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bmp);
try {
return SaveToJPGFile(bmp, path);
}
catch (Exception e){
return false;
}
finally {
bmp.recycle();
}
}
Now we compare with Beyond Compare:
comparing ocr to ocr1. take a look at the left-down corner. An example for pixels changing
I tried with png and got the following:
comparing png images
Hi In my application I am making an application in android in which I have to take screenshot of current activity and save it into sdcard.
For that i used one menu button named as download if i click the download i want to save the current activity into sdcard.
Now My problem is it's saving into sdcard but screenshot coming half.I want to download the whole screen and save it into sdcard.how to download the full activity.
Can anyone please help me how to solve this problem.
notify_image
public class notify_image extends Activity {
ImageView imageView;
Activity av=notify_image.this;
Bitmap b;
String strFileName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_image);
imageView = (ImageView) findViewById(R.id.iv_imageview);
Intent in = getIntent();
String title = in.getStringExtra("TAG_TITLE");
String url = in.getStringExtra("TAG_URL");
String name = in.getStringExtra("TAG_NAME");
String place = in.getStringExtra("TAG_PLACE");
String date = in.getStringExtra("TAG_DATE");
final String URL =url;
TextView stitle = (TextView) findViewById(R.id.tv_title);
TextView sname = (TextView) findViewById(R.id.tv_name);
TextView splace = (TextView) findViewById(R.id.tv_place);
TextView sdate = (TextView) findViewById(R.id.tv_date);
// displaying selected product name
stitle.setText(title);
sname.setText(name);
splace.setText(place);
sdate.setText(date);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
//creating button
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.downloads, menu);
return true;
}
//button on click function
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.downloads:
/*Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
*/
//captureScreen(v);
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
/*public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}*/
#SuppressWarnings("unused")
private static void savePic(Bitmap bitmap, String strFileName) {
//File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/print.png");
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
System.out.println("b is:"+bitmap);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
/*public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}*/
/*public Bitmap captureScreen(View v)
{
Bitmap bitmap = null;
try {
if(v!=null)
{
int width = v.getWidth();
int height = v.getHeight();
Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
v.draw(new Canvas(screenshot));
}
} catch (Exception e)
{
Log.d("captureScreen", "Failed");
}
return bitmap;
}
*/
/* public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}*/
/* public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}*/
//image url convert to bitmap
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
Thanks In Advance.
new updated code
public class notify_image extends Activity {
ImageView imageView;
Activity av=notify_image.this;
Bitmap b;
String strFileName;
Button download;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_image);
imageView = (ImageView) findViewById(R.id.iv_imageview);
download = (Button) findViewById(R.id.button1);
download();
Intent in = getIntent();
String title = in.getStringExtra("TAG_TITLE");
String url = in.getStringExtra("TAG_URL");
String name = in.getStringExtra("TAG_NAME");
String place = in.getStringExtra("TAG_PLACE");
String date = in.getStringExtra("TAG_DATE");
final String URL =url;
TextView stitle = (TextView) findViewById(R.id.tv_title);
TextView sname = (TextView) findViewById(R.id.tv_name);
TextView splace = (TextView) findViewById(R.id.tv_place);
TextView sdate = (TextView) findViewById(R.id.tv_date);
// displaying selected product name
stitle.setText(title);
sname.setText(name);
splace.setText(place);
sdate.setText(date);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
//creating button
/* public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.downloads, menu);
return true;
}
*/
//button on click function
/* public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.downloads:
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
//captureScreen(v);
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}*/
private void download() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
/*Intent nextScreen = new Intent(getApplicationContext(), KnowYourLeader.class);
startActivity(nextScreen);*/
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
}
private static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
/*public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}*/
#SuppressWarnings("unused")
private static void savePic(Bitmap bitmap, String strFileName) {
//File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/print.png");
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
System.out.println("b is:"+bitmap);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
/*public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}*/
/*public Bitmap captureScreen(View v)
{
Bitmap bitmap = null;
try {
if(v!=null)
{
int width = v.getWidth();
int height = v.getHeight();
Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
v.draw(new Canvas(screenshot));
}
} catch (Exception e)
{
Log.d("captureScreen", "Failed");
}
return bitmap;
}
*/
/* public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}*/
/* public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}*/
//image url convert to bitmap
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
Here is the code that allowed my screen shot to be stored on sd card and used later for whatever your needs are, you can achieve it with following code:
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then, when you need to access use something like this:
Uri uri = Uri.fromFile(new File(mPath));
Try out below code to capture the whole screen and save as bitmap.:
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "print.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();
}
Hope this will help you.
Here is my code when I am writing to the file
Bitmap bitmap;
InputStream is;
try
{
is = (InputStream) new URL(myUrl).getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
//program crashing here
File f = File.createTempFile(myUrl,null,MyApplication.getAppContext().getCacheDir());
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch(Exception e)
{
bitmap = null;
}
And here is my code reading from the same file
Bitmap bitmap;
try
{
File f = new File(myUrl);
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bitmapArr = new byte[bis.available()];
bis.read(bitmapArr);
bitmap = BitmapFactory.decodeByteArray(bitmapArr, 0, bitmapArr.length);
bis.close();
fis.close();
}
catch(Exception e)
{
bitmap = null;
}
The program is crashing at the creation of the temp file in the first chunk of code.
EDIT: I am getting a libcore.io.ErrnoException
UPDATE: I found the problem and fixed it, for anyone interested see below.
I changed it to use the openFileOutput(String, int), and openFileInput(String) methods, I should have done it this way right from the beginning.
The following is working code to decode an input stream from a url containing an image into a bitmap, compress the bitmap and store it into a file, and to retrieve said bitmap from that file later.
Bitmap bitmap;
InputStream is;
try
{
is = (InputStream) new URL(myUrl).getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
String filename = "file"
FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
}
catch(Exception e)
{
bitmap = null;
}
and
Bitmap bitmap;
try
{
String filename = "file";
FileInputStream fis = this.openFileInput(filename);
bitmap = BitmapFactory.decodeStream(fis);
fis.close();
}
catch(Exception e)
{
bitmap = null;
}
I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String
I want to download image from url and store in sdcard's folder.If folder is not exist make folder and save it.But its giving following exception:
java.io.FileNotFoundException: /mnt/sdcard (Is a directory)
The message is clear. /mnt/sdcard is a directory not a file. You need to create FileOutputStream that writes to a non-directory path.
For example:
//Setting up cache directory to store the image
File cacheDir=new File(context.getCacheDir(),"cache_folder");
// Check if cache folder exists, otherwise create folder.
if(!cacheDir.exists())cacheDir.mkdirs();
// Setting up file to write the image to.
File f=new File(cacheDir, "img.png");
// Open InputStream to download the image.
InputStream is=new URL(url).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
HelperUtil.CopyStream(is, os);
...
/**
* Copy all data from InputStream and write using OutputStream
* #param is InputStream
* #param os OutputStream
*/
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
try something like this
String image_URL="http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=http%3A%2F%2Fandroid-er.blogspot.com%2F";
String extStorageDirectory;
File file;
Bitmap bm;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
}else{
file=YourActivity.this.getCacheDir();
}
if(!file.exists())
file.mkdirs();
extStorageDirectory+="Your FolderName/yourimagename.PNG";
File imageFile = new File(extStorageDirectory);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
if(bitmap!=null){
imageview.setImageBitmap(bitmap);
}else{
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_URL, bmOptions);
imageview.setImageBitmap(bm);
OutputStream outStream = null;
file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");
file=new File(extStorageDirectory, "Your FolderName/yourimagename.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
where method are as
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}catch (Exception ex){
Log.e("error",ex.toString());
}
return inputStream;
}
You are giving wrong path when triying to save the picture. IT seems that you use "/mnt/sdcard" whereas it should be something like "/mnt/sdcard/image.jpg"
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_url, bmOptions);
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString() + "/image_folder";
OutputStream outStream = null;
File wallpaperDirectory = new File(extStorageDirectory);
wallpaperDirectory.mkdirs();
File outputFile = new File(wallpaperDirectory, "image.PNG");
try {
outStream = new FileOutputStream(outputFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
Try this one, that will return the External memory if it is exist, otherwise it will return the phone memory directory. The constructor takes Context and the name of the folder that you want to create as parameters. And also try this link, its quite nice stuff about what you need. Image Loader
public class FileCache {
private File cacheDir;
private String applicationDirectory = Config.applicationMainFolder;
public FileCache(Context context, String folderName){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(context.getExternalFilesDir(null), applicationDirectory + folderName);
else
cacheDir = new File(context.getCacheDir(), applicationDirectory + folderName);
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
use this
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File file=new File(Environment.getExternalStorageDirectory()+path);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, bytes);
byte b[] = bytes.toByteArray();
try
{
FileOutputStream fos = new FileOutputStream(file);
fos.write(b);
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
path will be your folder in sdcard and bitamp is object of image