从应用程序动态保存图像到SD卡

时间:2012-08-18 06:15:49

标签: android android-sdcard

我正在制作一个图库,我在其中加载(在运行时)资产文件夹中的图像。现在我想在点击事件中将图像保存到SD卡。

例如:当应用程序启动时,用户会看到图像,他们可以滚动图像并查看它们(此部分已完成)。问题是图片是在我自己的图库视图中动态加载的。我没有硬编码。

我想将它保存到SD卡。但我没有硬编码的图像路径。可以有任意数量的图像。

 private void CopyAssets() {
        AssetManager assetManager = getAssets();
        InputStream in=null;
    String[] files = null;
        try {
            files = assetManager.list("image");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        for(String filename : files) {


                try {
                    in = assetManager.open(filename);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
        try {
                String dirName = Environment.getExternalStorageDirectory().toString(); 
                File newFile = new File(dirName); 
                newFile.mkdirs(); 

        OutputStream out = new FileOutputStream(newFile);
        System.out.println("in tryyyy");

                copyFile(in, out);
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch(Exception e) {
                Log.e("tag", e.getMessage());
        }

我试过上面的方法,我不想将所有图像复制到SD卡上。但只有用户从画廊中选择的那个太动态了。因为会有很多图像。对每个图像路径进行硬编码将很困难。

在Android中有什么方法可以通过它获取字符串中的当前图像路径或URI吗?什么是View v = this.getCurrentFocus();?它又回归了什么?

2 个答案:

答案 0 :(得分:0)

GalleryAdapterView延伸,就像在adapterView上一样,您可以为选择项目时添加一个监听器。

您知道选择了哪个项目,使用它来将您想要的图像复制到SD卡。

为了更好地理解如何为adapterView实现适配器,请观看“the world of listView”视频。您可能希望将路径放入viewHolder(取决于您的代码和设计)。

答案 1 :(得分:0)

这是我创建的一个方法,允许您将图像(位图)保存到内存中。参数需要一个位图对象和该对象的文件名。

public void writeBitmapToMemory(String filename, Bitmap bitmap) {
        FileOutputStream fos;
        // Use the compress method on the Bitmap object to write image to the OutputStream
        try {
            fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
            // Writing the bitmap to the output stream
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();

        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();


        } 
        catch (IOException e) {
            e.printStackTrace();


        }

    }

我希望这会有所帮助。

相关问题