将位图图像保存到外部存储器并将其位置存储在sqlite中以便以后检索

时间:2014-02-01 20:29:37

标签: android sqlite bitmap

我有一个简单的应用程序,它从API获取信息并将其存储为对象并显示在列表视图中,此时我的对象包含指向图像的URL链接,我想知道如何将位图图像存储到设备并将url链接替换为设备上文件位置的链接,这是我当前的活动代码:

    protected Bitmap doInBackground(String... params) {
        // in the background:

        // get the address from the params:
        String address = params[0];

        HttpURLConnection connection = null;
        InputStream stream = null;
        ByteArrayOutputStream outputStream = null;

        // the bitmap will go here:
        Bitmap b = null;


        try {
            // build the URL:
            URL url = new URL(address);
            // open a connection:
            connection = (HttpURLConnection) url.openConnection();

            // check the connection response code:
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                // not good..
                return null;
            }

            // the input stream:
            stream = connection.getInputStream();

            // get the length:
            int length = connection.getContentLength();
            // tell the progress dialog the length:
            // this CAN (!!) be modified outside the UI thread !!!
            progressDialog.setMax(length);

            // a stream to hold the read bytes.
            // (like the StringBuilder we used before)
            outputStream = new ByteArrayOutputStream();

            // a byte buffer for reading the stream in 1024 bytes chunks:
            byte[] buffer = new byte[1024];

            int totalBytesRead = 0;
            int bytesRead = 0;

            // read the bytes from the stream
            while ((bytesRead = stream.read(buffer, 0, buffer.length)) != -1) {
                totalBytesRead += bytesRead;
                outputStream.write(buffer, 0, bytesRead);

                // notify the UI thread on the progress so far:
                publishProgress(totalBytesRead);
                Log.d("TAG", "progress: " + totalBytesRead + " / " + length);
            }

            // flush the output stream - write all the pending bytes in its
            // internal buffer.
            outputStream.flush();

            // get a byte array out of the outputStream
            // theses are the bitmap bytes
            imageBytes = outputStream.toByteArray();

            // use the BitmapFactory to convert it to a bitmap
            b = BitmapFactory.decodeByteArray(imageBytes, 0, length);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                // close connection:
                connection.disconnect();
            }
            if (outputStream != null) {
                try {
                    // close output stream:
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return b;
    }

    protected void onPostExecute(Bitmap result) {
        // back on the UI thread

        // close the progress dialog
        progressDialog.dismiss();

        ImageView imageView = (ImageView) findViewById(R.id.page_edit_image);

        if (result == null) {
            // no image loaded - display the default image
            imageView.setImageResource(R.drawable.ic_launcher);
            Toast.makeText(AddEditActivity.this, "error loading image",
                    Toast.LENGTH_LONG).show();
        } else {
            // set the image bitmap:
            imageView.setImageBitmap(result);

//this is where i would like to save the image to the device some how and put its location in the object instead of giving it a url for downloading it dynamicaly


        }
    };
}


    Movie movie = new Movie(subject, body, year, /* i would like this to be a link to a location on the device*/ urlPic);   

    Log.d("year check", movie.getYear()+"");
    Log.d("movie attributes", subject+", "+year+", "+rating+", "+watched);

    dbhandler.insertMovie(movie);

2 个答案:

答案 0 :(得分:1)

只需输入此代码&用此替换你的Post Execute。

  

protected void onPostExecute(Bitmap result){           //回到UI线程

    // close the progress dialog
    progressDialog.dismiss();

    ImageView imageView = (ImageView) findViewById(R.id.page_edit_image);

    if (result == null) {
        // no image loaded - display the default image
        imageView.setImageResource(R.drawable.ic_launcher);
        Toast.makeText(AddEditActivity.this, "error loading image",
                Toast.LENGTH_LONG).show();
    } else {
        // set the image bitmap:
        imageView.setImageBitmap(result);
     

//这是我想将图像保存到设备的方法   并将其位置放在对象中,而不是为其提供URL   动态下载

     

<强> SaveImage(结果);

    }
}
     

private void SaveImage(Bitmap finalBitmap){

  String root = Environment.getExternalStorageDirectory().toString();
  File myDir = new File(root + "/demo_images");    
  myDir.mkdirs();
  Random generator = new Random();
  int n = 10000;
  n = generator.nextInt(n);
  fname = "Image-"+ n +".jpg";
  file = new File (myDir, fname);
     

//下面的代码将为您提供TextView

中的完整路径      

<强>&GT; txtPath1.setText(file.getAbsolutePath());

  if (file.exists ()) file.delete (); 
  try {
         FileOutputStream out = new FileOutputStream(file);
         finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
         out.flush();
         out.close();

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

答案 1 :(得分:0)

您可以尝试将其更改为您的规格

File folder = new File(Environment.getExternalStorageDirectory().toString());
                 boolean success = false;
                 if (!folder.exists()) 
                 {
                     success = folder.mkdirs();
                 }

                 System.out.println(success+"folder");

                 File file = new File(Environment.getExternalStorageDirectory().toString() + "/sample.png");

             if ( !file.exists() )
             {
                   try {
                    success = file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
             }

             System.out.println(success+"file");



             FileOutputStream ostream = null;
                try
                {
                ostream = new FileOutputStream(file);


                result.compress(Bitmap.CompressFormat.PNG, 100, ostream);
                //bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
                   //ostream.flush();
                    //ostream.close();
                }catch (NullPointerException e) 
                {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Null error", Toast.LENGTH_SHORT).show();
                }

                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "File error", Toast.LENGTH_SHORT).show();
                }

                catch (IOException e) 
                {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "IO error", Toast.LENGTH_SHORT).show();
                }

            }

以及您可以使用的路径

file.getAbsolutePath()

将返回一个可以插入数据库的字符串