2012-05-11 2 views
2
package com.sample.downloadImage; 
import java.io.BufferedInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLConnection; 
import org.apache.http.util.ByteArrayBuffer; 
import android.app.Activity; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.widget.ImageView; 

public class downloadImage extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    Bitmap bitmap = DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg"); 


     ImageView img = (ImageView) findViewById(R.id.img); 
     img.setImageBitmap(bitmap); 
    } 

    private InputStream OpenHttpConnection(String urlString) 
    throws IOException 
    { 
     InputStream in = null; 
     int response = -1; 

     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 

     if (!(conn instanceof HttpURLConnection))      
      throw new IOException("Not an HTTP connection"); 

     try{ 
      HttpURLConnection httpConn = (HttpURLConnection) conn; 
      httpConn.setAllowUserInteraction(false); 
      httpConn.setInstanceFollowRedirects(true); 
      httpConn.setRequestMethod("GET"); 
      httpConn.connect(); 
      response = httpConn.getResponseCode();     
      if (response == HttpURLConnection.HTTP_OK) { 
       in = httpConn.getInputStream();         
      }      
     } 
     catch (Exception ex) 
     { 
      throw new IOException("Error connecting");    
     } 
     return in;  
    } 
    private Bitmap DownloadImage(String URL) 
    {   
     Bitmap bitmap = null; 
     InputStream in = null; 



     try { 
      in = OpenHttpConnection(URL); 
      BufferedInputStream bis = new BufferedInputStream(in, 8190); 

      ByteArrayBuffer baf = new ByteArrayBuffer(50); 
      int current = 0; 
      while ((current = bis.read()) != -1) 
      { 
       baf.append((byte)current); 
      } 
      byte[] imageData = baf.toByteArray(); 
      bitmap =BitmapFactory.decodeByteArray(imageData, 0, imageData.length); 
      in.close(); 
     } 
     catch (IOException e1) 
     { 

      e1.printStackTrace(); 
     } 
     return bitmap;     
    } 
} 

хочет retrive изображения с сервера, поэтому я попытался опубликовать изображение в сервере и retrive через URL, но это работает хорошо для маленьких изображений, а когда приходит большое изображение более 60kb, может кто-нибудь дать мысль решить проблемуRetriving изображения с сервера на андроид приложение

package com.sample.downloadImage; 
import java.io.BufferedInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLConnection; 
import org.apache.http.util.ByteArrayBuffer; 
import android.app.Activity; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.widget.ImageView; 

public class downloadImage extends Activity { 

    HttpURLConnection httpConn; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    Bitmap bitmap = DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg"); 


     ImageView img = (ImageView) findViewById(R.id.img); 
     img.setImageBitmap(bitmap); 
    } 

    private InputStream OpenHttpConnection(String urlString) 
    throws IOException 
    { 
     InputStream in = null; 
     int response = -1; 

     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 

     if (!(conn instanceof HttpURLConnection))      
      throw new IOException("Not an HTTP connection"); 

     try{ 
      httpConn = (HttpURLConnection) conn; 
      httpConn.setAllowUserInteraction(false); 
      httpConn.setInstanceFollowRedirects(true); 
      httpConn.setRequestMethod("GET"); 
      httpConn.connect(); 
      response = httpConn.getResponseCode();     
      if (response == HttpURLConnection.HTTP_OK) { 
       in = httpConn.getInputStream(); 

       DownloadImage(urlString); 
      }      
     } 
     catch (Exception ex) 
     { 
      throw new IOException("Error connecting");    
     } 
     return in;  
    } 

    private Bitmap DownloadImage(String URL) 
    {   
     Bitmap bitmap = null; 
     //InputStream is = null; 
     InputStream in; 
     try 
     { 
      in = httpConn.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(in, 3 *1024); 
      ByteArrayBuffer baf = new ByteArrayBuffer(50); 
      int current = 0; 
      while ((current = bis.read()) != -1) 
      { 
       baf.append((byte)current); 
       byte[] imageData = baf.toByteArray(); 
       bitmap =BitmapFactory.decodeByteArray(imageData, 0, imageData.length); 
       return bitmap;  
      } 
     } 
     catch (IOException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return bitmap; 
      } 
} 
+0

http://stackoverflow.com/questions/4996470/load-large-image- from-server-on-android –

ответ

3

форма: Load Large Image from server on Android

это не редкость для BitmapFactory.decodeFromStream(), чтобы отказаться и просто возвращает нуль при подключении непосредственно к InputStream из удаленное соединение. Внутри, если вы не предоставили метод BufferedInputStream для этого метода, он будет переносить предоставленный поток в один с размером буфера 16384. Один из вариантов, который иногда работает, - передать BufferedInputStream с большим размером буфера, например:

BufferedInputStream bis = new BufferedInputStream (is, 32 * 1024); Более универсально эффективный метод, чтобы загрузить файл полностью, а затем декодировать данные, как это:

InputStream is = connection.getInputStream(); 
BufferedInputStream bis = new BufferedInputStream(is, 8190); 

ByteArrayBuffer baf = new ByteArrayBuffer(50); 
int current = 0; 
while ((current = bis.read()) != -1) { 
    baf.append((byte)current); 
} 
byte[] imageData = baf.toByteArray(); 
BitmapFactory.decodeByteArray(imageData, 0, imageData.length); 

FYI, размеры буфера в этом примере несколько произвольны. Как было сказано в других ответах, фантастическая идея не сохранять изображение, размер которого в памяти дольше, чем нужно. Возможно, вы захотите записать его непосредственно в файл и отобразить версию с пониженной дискретизацией.

Надеюсь, что это поможет!

+0

1- http://blog.sptechnolab.com/2011/03/04/android/android-load-image-from-url/ . 2- http://developer.android.com/training/displaying-bitmaps/index.html –

+0

InputStream is = connection.getInputStream(); соединение, используемое в приведенном выше, означает объект HttpURLConnection или объект URLConnection – user1389233

+0

. Я получаю сообщение об ошибке в этом месте, когда я иду на отладку, «InputStream is = connection.getInputStream();« wher должен передать URL-адрес в этом раздел – user1389233

0

Посмотрите эту страницу и загрузите образец кода. он будет решать ваши проблемы

http://developer.android.com/training/displaying-bitmaps/index.html

+0

не могли бы вы дать мне другую возможную ссылку, чтобы узнать о загрузке большого размера изображения в безопасном виде? – user1389233

2
+0

Я пробовал с приведенными выше ссылками, которые поддерживают небольшие изображения, но я задерживаюсь с изображениями большего размера – user1389233