【问题标题】:How to get bitmap from sdcard如何从 sdcard 中获取位图
【发布时间】:2014-04-04 15:58:07
【问题描述】:

我有一个从 URL 获取位图并将它们存储在 sd 卡中的函数。但我无法找回它们。我将不胜感激。

我的代码如下:

private static Bitmap getDrawableFromUrl(final String Url,final String videoID) {
    Drawable d = null;
    Bitmap bitmap = null;
    bitmap = memoryCache.get(Url);
    File f = fileCache.getFile(videoID);
    bitmap = decodeFile(f);
    if(bitmap != null)
    {
        Log.v(DBUG, "Seems got the file::");
        return bitmap;
    }
    if(bitmap == null){
        try {
            System.out.println(Url);
            d = Drawable.createFromStream(((java.io.InputStream) new java.net.URL(Url).getContent()),"name");
            BitmapDrawable b = ((BitmapDrawable) d);
            bitmap = b.getBitmap();
            memoryCache.put(Url, bitmap);
            fileCache.put(videoID, bitmap);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    return bitmap;
}

这里是 decodeFile 函数。这是一个从sdcard解码文件的功能..


private static Bitmap decodeFile(File f){
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=70;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

我有一个文件缓存类来处理目录选择等等。如下::


public class FileCache {

private File cacheDir;
private final static String DEBUG = FileCache.class.getSimpleName();

public FileCache(Context context){
    //Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TempImages1");
    else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url){
    Log.v(DEBUG, "tring to get file f:::");
    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();
}

public void put(String url, Bitmap bitmap) {
    // TODO Auto-generated method stub
    Log.v(DEBUG, "It has been called::::");
    File dest = new File(cacheDir, url);
    try {
        FileOutputStream out;
        out = new FileOutputStream(dest);
        bitmap.compress(CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    }catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
} 
}

【问题讨论】:

  • 对不起,但是什么,到底是行不通的?你期望什么,你会得到什么?

标签: android bitmap android-sdcard


【解决方案1】:
public Bitmap createBitMap(){
    File file = new File("your sdcard path");
    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    return bitmap;
}

【讨论】:

    【解决方案2】:

    您的问题不是很清楚,但我知道问题是从 url 中检索位图,对吗?也许这是一个特殊的解决方案,但您可以尝试使用下一种方法获取图像/位图,在这种情况下,您可以解决您的问题:

        private class GetImageRequestCamera extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... body) 
        { 
               ///Get
               HttpGet httpGet = new HttpGet(body[0]);               
               httpGet.addHeader("Accept", "text/plain");
               httpGet.setHeader("Content-type", "text/plain");
    
               HttpParams httpParameters = new BasicHttpParams();
               // Set the timeout in milliseconds until a connection is established.
               // The default value is zero, that means the timeout is not used. 
               int timeoutConnection = 4000;
               HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
               // Set the default socket timeout (SO_TIMEOUT) 
               // in milliseconds which is the timeout for waiting for data.
               int timeoutSocket = 4000;
               HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
               HttpClient httpClient = new DefaultHttpClient(httpParameters);
    
               HttpResponse httpResponse;
               Bitmap bmp=null;
    
                try 
                {
                    httpResponse = httpClient.execute(httpGet);
    
                    if(httpResponse!=null)
                    {
                        try 
                        {
                            HttpEntity entity = httpResponse.getEntity();
                            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                            InputStream instream = bufHttpEntity.getContent();
                            bmp = BitmapFactory.decodeStream(instream);
                        }
                        catch (IOException e) 
                        { 
                            e.printStackTrace(); 
                            return null;
                        }
                        catch (Exception e) 
                        { 
                            e.printStackTrace();
                            return null;
                        }
                    }
                } 
                 catch(ConnectTimeoutException e){
                        Log.e("Timeout Exception: ", e.toString());
                        return null;
                } catch(SocketTimeoutException ste){  
                    Log.e("Timeout Exception: ", ste.toString());
                    return null;
                }
                catch (ClientProtocolException e1) {
                    e1.printStackTrace();
                    return null;
                } catch (IOException e1) {
                    e1.printStackTrace();
                    return null;
                }
    
          return bmp;
        }
    
            @Override
            protected void onPostExecute(Bitmap image) {
    
                try
                {
                    if(image!=null)
                    {
                        snapshot.setImageBitmap(image);
                        snapshot.setVisibility(View.VISIBLE);
                    }
                }catch(Exception e)
                {
                }
            }
    }
    

    此方法从 url 获取一个图像/位图。而且我用的方法和你的方法完全不一样。

    您将需要使用下一次调用来调用此方法:

    String[] body= new String[1];
    body[0]= url;           
    new GetImageRequestCamera().execute(body);  
    

    在 onPostExecute() 中,对象“快照”是一个 ImageView 对象。试试看!让我们看看。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2012-07-02
      • 2016-11-19
      • 1970-01-01
      相关资源
      最近更新 更多