简体   繁体   English

图像未保存到SD卡中的Android设备

[英]image is not saving to android device in Sd card

package com.lociiapp;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.example.imageslideshow.R;

public class recciverfullimageActivty extends Activity {
    String reccvierid;
    Context context;
    ImageView recciverimage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        Intent myintent = getIntent();
        reccvierid = myintent.getStringExtra("reccvierid");
        recciverimage = (ImageView) findViewById(R.id.recciverImage);
        String myfinalpathare = reccvierid;
        Toast.makeText(getApplicationContext(), reccvierid, 10000).show();
        String imagepathe = "http://api.lociiapp.com/TransientStorage/"
                + myfinalpathare + ".jpg";

        try {
            saveImage(imagepathe);

            Log.e("****************************", "Sucess");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void saveImage(String urlPath) throws Exception {
        String fileName = "test.jpg";
        File folder = new File("/sdcard/LociiImages/");
        // have the object build the directory structure, if needed.
        folder.mkdirs();

        final File output = new File(folder, fileName);
        if (output.exists()) {
            output.delete();
        }

        InputStream stream = null;
        FileOutputStream fos = null;
        try {

            URL url = new URL(urlPath);
            stream = url.openConnection().getInputStream();
            // InputStreamReader reader = new InputStreamReader(stream);
            DataInputStream dis = new DataInputStream(url.openConnection()
                    .getInputStream());
            byte[] fileData = new byte[url.openConnection().getContentLength()];
            for (int x = 0; x < fileData.length; x++) { // fill byte array with
                                                        // bytes from the data
                                                        // input stream
                fileData[x] = dis.readByte();

            }
            dis.close();
            fos = new FileOutputStream(output.getPath());
            fos.write(fileData);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

This is My code I am trying to save Image which is coming from server we have Image Url . 这是我的代码,我试图保存来自具有Image Url的服务器的图像。 when i Run this Code then Folder is creating in Sd card But image is not downloading on Save in Sd care please help and tell where i am doing wrong . 当我运行此代码时,则在SD卡中创建了文件夹,但是在SD保存中没有下载图像,请帮助并告诉我我做错了什么。

Your checklist should be as follows: 您的清单应如下:

A. Make sure you have the right permissions : :确保您具有正确的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" /> 


B. Move networking and file IO logic to non-UI thread : B.将网络和文件IO逻辑移至非UI线程

new AsyncTask<Params, Progress, Result>() {
    @Override protected Result doInBackground() {
         saveImage(imagepathe);
    } 
    @Override protected void onPostExecute(String result) {
        // update UI here
    }
}.execute(params);


C. Do not read one byte at the time. C. 请勿一次读取一个字节。 It is probably not the source of your problem but it does make your solution much slower than it can be: 它可能不是问题的根源,但确实会使您的解决方案比实际速度慢得多:

Instead of: 代替:

for(;;)  {
   fileData[x] = dis.readByte();
}

Do this: 做这个:

URL u = new URL(url);
URLConnection connection = u.openConnection();
byte[] buffer = new byte[connection.getContentLength()];
stream.readFully(buffer); // <------------- read all at once
stream.close();



D. And , finally, consider using Picasso for the job: D.最后,考虑使用毕加索来完成这项工作:

Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)


Nowadays you just no not need to write that much code to get were you're going.. 如今,您只需要编写那么多代码就可以了。

Try this.. 尝试这个..

Call like below instead of saveImage(imagepathe); 像下面这样调用而不是saveImage(imagepathe);

myAsyncTask myWebFetch = new myAsyncTask();
myWebFetch.execute();

and myAsyncTask.class myAsyncTask.class

class myAsyncTask extends AsyncTask<Void, Void, Void>    {

    public ProgressDialog dialog;
    myAsyncTask()   
    {
        dialog = new ProgressDialog(webview.this);
        dialog.setMessage("Loading image...");
        dialog.setCancelable(true);
        dialog.setIndeterminate(true);
    }
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        dialog.dismiss();

    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.show();
    }
    protected Void doInBackground(Void... arg0) {
       try {

            InputStream stream = null;
            URL url = new URL("http://api.lociiapp.com/TransientStorage/286.jpg");
            URLConnection connection = url.openConnection();
            try {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                File SDCardRoot = Environment.getExternalStorageDirectory();
                File myDir = new File(SDCardRoot + "/LociiImages");
                myDir.mkdirs();

                File file = new File(myDir,"test.jpg");

                FileOutputStream fileOutput = new FileOutputStream(file);

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();
                }

                byte[] buffer = new byte[1024];
                int bufferLength = 0; 

                while ( (bufferLength = stream.read(buffer)) > 0 ) {
                    fileOutput.write(buffer, 0, bufferLength);
                }
                fileOutput.close();

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }  
}

EDIT 编辑

String imagePath = Environment.getExternalStorageDirectory().toString() + "/LociiImages/test.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM