簡體   English   中英

寫/讀gif內部存儲

[英]Writing/Reading gif internal storage

我正在嘗試從URL中加載gif以在Imageview中顯示,將其存儲在內部存儲中,然后再次讀取它。 但它拒絕存儲圖像或讀取它,不知道哪一個,因為我沒有例外。 將圖像加載到imageview可以正常工作。 下面的第一個方法(loadImage())

public Bitmap loadImage(String url){
    Bitmap bm = null;
    URL request;
    try {
        if(url!=null){
            request = new URL(url);
            InputStream is = request.openStream();
            bm = BitmapFactory.decodeStream(is);
            is.close();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bm;
}

public String writeGifToInternalStorage (Bitmap outputImage) {
    try {
        String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
        ByteBuffer byteBuffer = ByteBuffer.allocate(outputImage.getByteCount());
        outputImage.copyPixelsToBuffer(byteBuffer);
        byteBuffer.flip();
        byte[] data = new byte[byteBuffer.limit()];
        byteBuffer.get(data);
        FileOutputStream fos =  ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
        fos.write(data);
        fos.close();
        return fileName;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public Bitmap readFileFromInternalStorage(String filename) {
    if (filename == null) return null;
        FileInputStream fis;
    try {
        fis = ctx.openFileInput(filename);
        return BitmapFactory.decodeStream(fis);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

什么想法都錯了?

您的方法readFileFromInternalStorage從文件系統中讀取編碼圖像。 此圖像文件應該是您從服務器收到的內容。

為此,您需要在從服務器接收圖像時保存圖像,例如:

InputStream is = new BufferedInputStream(request.openStream());
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int red = 0;
while ((red = is.read(buffer)) != -1) {
    fos.write(buffer,0, red);
}
fos.close();
is.close();

然后,您的圖像將保存到磁盤,您可以使用readFileFromInternalStorage方法打開它。

另外,如果您使用HttpClient而不是URL,我寫了一個單行程序來下載文件: Android下載二進制文件問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM