写/读gif内部存储

时间:2013-12-05 15:33:15

标签: java android

我正在尝试从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;
}

任何想法都错了?

1 个答案:

答案 0 :(得分:2)

您的方法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 download binary file problems