0

大家好,我想从 url 将图像的字节格式存储在我的数据库中。我正在使用此代码

     URL url = new
    URL("http://images.11bestbuy.com/images/small_17385013870957.jpg");
    InputStream anyfile = url.openStream();

但它对我来说显示错误。

4

2 回答 2

1

您可以解码 aBitmap然后将其转换为字节数组:

public byte[] downloadImage() throws Exception{

      URL url = new URL("http://images.11bestbuy.com/images/small_17385013870957.jpg");
      HttpURLConnection con = (HttpURLConnection) url.openConnection();
      con.setRequestMethod("GET");
      con.setReadTimeout(10000);
      con.setConnectTimeout(10000);

      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      try {
        Bitmap b = BitmapFactory.decodeStream(con.getInputStream());
        b.compress(Bitmap.CompressFormat.JPEG,100,bos);
      } finally {
        con.disconnect();
      }

      return bos.toByteArray();
 }

您可以将字节数组存储在BLOBSQLite 数据库的类型记录中。

于 2013-07-12T05:36:14.747 回答
0

试试这个它对我有用

          static private Bitmap downloadBitmap(String url) throws IOException {
    HttpUriRequest request = new HttpGet(url);
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();  
    if (statusCode == 200) {
        System.out.println("kjklcmklxc");
      HttpEntity entity = response.getEntity();
      byte[] bytes = EntityUtils.toByteArray(entity);

      Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
          bytes.length);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byt_aary_outpt_strm);
    dh.delete(DatabaseHelper.Image_handler, null, null);
      bitmapdata = byt_aary_outpt_strm.toByteArray();
      System.out.println("bitmap of image converted image");
      for(int i =0 ; i<bitmapdata.length;i++){
          convert_save_byte_str = convert_save_byte_str+bitmapdata[i];
      }
      System.out.println("njdsfnh"+convert_save_byte_str);
      ContentValues userdetailValues = new ContentValues();

        userdetailValues.put("image_byte", convert_save_byte_str);
        System.out.println("between put and insert");
        dh.insert(DatabaseHelper.Image_handler, null, userdetailValues); 
        cursor = dh.rawQuery("SELECT _id, image_byte FROM image_database",null);
        int i=0;
        if (cursor.moveToFirst()) {
            do {


               // get  the  data into array,or class variable   
                bb = cursor.getBlob(cursor.getColumnIndex(DatabaseHelper.Image_handeler_column));
                //System.out.println("productid"+data);
                //intent.putExtra("product_id", data);
                System.out.print("bytengkfgkjgk"+bb[i]);

            i++;
            } while (cursor.moveToNext());
        }

      return bitmap;    
    } else {
      throw new IOException("Download failed, HTTP response code "
          + statusCode + " - " + statusLine.getReasonPhrase());
    }
  }
于 2013-07-12T05:32:36.193 回答