inputstream.read在下载大的图像时,没有响应(大小> 300K) [英] inputstream.read has no response when downloading large image(size > 300K)

查看:263
本文介绍了inputstream.read在下载大的图像时,没有响应(大小> 300K)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜的家伙。下载大尺寸images.It的很奇怪,当我有一个问题,而读取字节流始终没有反应。
我的code是如下,任何建议是值得欢迎的。

 公共类ImageTestActivity延伸活动{    公共静态最终诠释IMAGE_BUFFER_SIZE = 8 * 1024;
    公共静态最终诠释MAX_REQUEST_WIDTH = 480;
    公共静态最终诠释MAX_REQUEST_HEIGHT = 480;
    私有静态最后弦乐TAG = ImageTestActivity.class.getSimpleName();
    私有静态最终诠释HTTP_CONNECT_TIMEOUT = 10000;    私有静态最终诠释CONTENT_IMAGE_OFFSET = 80;
    私人显示填充mDisplay = NULL;    私人ImageView的mContentPic = NULL;    私人位图mContentPicBitmap = NULL;    私人RefreshAsyncTask mRefreshTask = NULL;    / **当第一次创建活动调用。 * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        mContentPic =(ImageView的)findViewById(R.id.wimessage_content_picture);
        填充mDisplay = getWindowManager()getDefaultDisplay()。
        mRefreshTask =新RefreshAsyncTask();
        mRefreshTask.execute(http://218.240.46.38/img/201206/28/-980416187.jpeg);
    }    私人无效initImageSetting(位图BM){
        如果(BM == NULL){
            返回;
        }
        INT scrWidth = mDisplay.getWidth();
        INT scrHeight = mDisplay.getHeight();
        INT imageHeight = bm.getHeight();
        INT imageWidth = bm.getWidth();
        / *如果(imageHeight * 3'; imageWidth * 2){
             *这是很奇怪的,当画面长宽比小于3:2,
             *执行下列code会造成画面不显示
             *
            返回;
        } * /        mContentPic.setAdjustViewBounds(真);
        mContentPic.setMaxWidth(scrWidth - CONTENT_IMAGE_OFFSET);
        如果((imageWidth< = scrWidth - CONTENT_IMAGE_OFFSET)||(imageHeight< scrHeight)){
            mContentPic.setMaxHeight(imageHeight);
        }其他{
            mContentPic.setMaxHeight((INT)((浮点)imageHeight *(scrWidth - CONTENT_IMAGE_OFFSET)/ imageWidth));
        }
    }    公共静态的byte []的getBytes(的BufferedInputStream插播广告)抛出IOException
        ByteArrayOutputStream outStream =新ByteArrayOutputStream();
        的BufferedOutputStream出=新的BufferedOutputStream(outStream,IMAGE_BUFFER_SIZE);
        字节[]缓冲区=新的字节[IMAGE_BUFFER_SIZE]        INT LEN = inStream.read(缓冲);
        Log.i(TAG---开始---);
        而(LEN!= -1){
            Log.i(TAG,((整数)LEN)的ToString());
            尝试{
                out.write(缓冲液,0,LEN);
            }赶上(抛出IndexOutOfBoundsException E){
                e.printStackTrace();
            }
            LEN = inStream.read(缓冲液);
        }        Log.i(TAG---结束---);
        了out.flush();
        out.close();
        inStream.close();        返回outStream.toByteArray();
    }    公共静态INT calculateInSampleSize(BitmapFactory.Options选项,
            INT reqWidth,诠释reqHeight){
        //原始高度和图像宽度
        最终诠释身高= options.outHeight;
        最终诠释宽度= options.outWidth;
        INT inSampleSize = 1;        如果(高度> reqHeight ||宽度GT; reqWidth){
            如果(宽>高度){
                inSampleSize = Math.round((浮点)高度/(浮点)reqHeight);
            }其他{
                inSampleSize = Math.round((浮点)宽/(浮点)reqWidth);
            }            //这提供的情况下,图像有一个奇怪的一些额外的逻辑
            //宽高比。例如,全景可以具有大得多的
            //宽度大于高度。在这种情况下,总像素仍可能
            //最终会被过大,以适应在舒适的记忆,所以我们应该
            //更积极与样本缩小图像(=大
            // inSampleSize)。            最终浮动totalPixels =宽*高;            //任何超过2倍的像素要求,我们将品尝下来
            // 进一步。
            最终浮动totalReqPixelsCap = reqWidth * reqHeight * 2;            而(totalPixels /(inSampleSize * inSampleSize)GT; totalReqPixelsCap){
                inSampleSize ++;
            }
        }
        返回inSampleSize;
    }    公共静态位图loadImageFromURL(字符串urlPath){
        尝试{
            网址URL =新的URL(urlPath);
            HttpURLConnection的连接=(HttpURLConnection类)url.openConnection();
            connection.setRequestMethod(GET);
            connection.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
            INT RSP code = connection.getResponse code();
            如果(RSP code == HttpStatus.SC_OK){
                // InputStream的时间= connection.getInputStream();
                位图位图= NULL;
                在BufferedInputStream为=新的BufferedInputStream(url.openStream(),IMAGE_BUFFER_SIZE);
                字节[]数据=的getBytes(中);
                附寄();
                如果(数据!= NULL){
                    尝试{
                        BitmapFactory.Options选项=新BitmapFactory.Options();
                        options.inJustDe codeBounds = TRUE;
                        options.inSampleSize = calculateInSampleSize(选项,MAX_REQUEST_WIDTH,MAX_REQUEST_HEIGHT);
                        options.inJustDe codeBounds = FALSE;
                        位= BitmapFactory.de codeByteArray的(数据,0,data.length,期权);
                    }赶上(OutOfMemoryError异常五){
                        e.printStackTrace();
                    }
                }其他{
                    Log.i(TAG,数据==空);
                }                connection.disconnect();
                返回位图;
            }其他{
                connection.disconnect();
                Log.i(TAG,RSP code =+ RSP code);
            }
        }赶上(MalformedURLException的E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        返回null;
    }    私有类RefreshAsyncTask扩展的AsyncTask<字符串,布尔值,布尔> {
        @覆盖
        保护布尔doInBackground(字符串...为arg0){
            mContentPicBitmap = loadImageFromURL(为arg0 [0]);
            返回true;
        }        @覆盖
        保护无效onPostExecute(布尔结果){
            super.onPostExecute(结果);
            如果(mContentPicBitmap!= NULL){
                initImageSetting(mContentPicBitmap);
                mContentPic.setImageBitmap(mContentPicBitmap);
            }
        }
    }
}


解决方案

试试这个我已经尝试用乌尔链接拿给我的ImageView图像

  BitmapFactory.Options bmOptions;
bmOptions =新BitmapFactory.Options();
bmOptions.inSampleSize = 1;
BM =的LoadImage(http://218.240.46.38/img/201206/28/-980416187.jpeg,bmOptions);
imageview.setImageBitmap(BM);

在这里methos 的LoadImage 为如下

给出

 私人位图的LoadImage(字符串URL,BitmapFactory.Options选项){
    位图位图= NULL;
    在的InputStream = NULL;
    尝试{
        在= OpenHttpConnection(URL);
        位= BitmapFactory.de codeStream(中,空,期权);
        附寄();
    }赶上(IOException异常E1){    }
   返回位图;
}
私人的InputStream OpenHttpConnection(字符串strURL)抛出IOException
     为InputStream的InputStream = NULL;
     网址URL =新的URL(strURL);
     康涅狄格州的URLConnection = url.openConnection();     尝试{
        HttpURLConnection的httpConn =(HttpURLConnection类)美国康涅狄格州;
        httpConn.setRequestMethod(GET);
        httpConn.connect();
        如果(httpConn.getResponse code()== HttpURLConnection.HTTP_OK){
            的InputStream = httpConn.getInputStream();
        }
     }赶上(例外前){     }
     返回InputStream的;
}

Hi guys. I have a problem when downloading large size images.It's very strange, while read bytes from stream always no response. My code is as follows, any suggestion is welcome.

public class ImageTestActivity extends Activity {

    public static final int IMAGE_BUFFER_SIZE = 8*1024;
    public static final int MAX_REQUEST_WIDTH = 480;
    public static final int MAX_REQUEST_HEIGHT = 480;
    private static final String TAG = ImageTestActivity.class.getSimpleName();
    private static final int HTTP_CONNECT_TIMEOUT = 10000;

    private static final int CONTENT_IMAGE_OFFSET = 80;
    private Display mDisplay = null;

    private ImageView mContentPic = null;

    private Bitmap mContentPicBitmap = null;

    private RefreshAsyncTask mRefreshTask = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        mContentPic = (ImageView)findViewById(R.id.wimessage_content_picture);
        mDisplay = getWindowManager().getDefaultDisplay();
        mRefreshTask = new RefreshAsyncTask();
        mRefreshTask.execute("http://218.240.46.38/img/201206/28/-980416187.jpeg");
    }    

    private void initImageSetting(Bitmap bm) {
        if (bm == null) {
            return;
        }
        int scrWidth = mDisplay.getWidth();
        int scrHeight = mDisplay.getHeight();
        int imageHeight = bm.getHeight();
        int imageWidth = bm.getWidth();
        /*if (imageHeight*3 < imageWidth*2) {
             * It is very strange, when the picture aspect ratio less than 3:2, 
             * execute the following code will cause the picture is not displayed
             *
            return;
        }*/

        mContentPic.setAdjustViewBounds(true);
        mContentPic.setMaxWidth(scrWidth - CONTENT_IMAGE_OFFSET);
        if ((imageWidth <= scrWidth - CONTENT_IMAGE_OFFSET) || (imageHeight < scrHeight)) {
            mContentPic.setMaxHeight(imageHeight);
        } else {
            mContentPic.setMaxHeight((int)((float)imageHeight * (scrWidth - CONTENT_IMAGE_OFFSET) / imageWidth));       
        }
    }

    public static byte[] getBytes(BufferedInputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream out = new BufferedOutputStream(outStream, IMAGE_BUFFER_SIZE);
        byte[] buffer = new byte[IMAGE_BUFFER_SIZE];

        int len = inStream.read(buffer);
        Log.i(TAG, "---start---");
        while (len != -1) {
            Log.i(TAG, ((Integer)len).toString());
            try {
                out.write(buffer, 0, len);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
            len = inStream.read(buffer);
        }

        Log.i(TAG, "---end---");
        out.flush();
        out.close();
        inStream.close();

        return outStream.toByteArray();
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }

            // This offers some additional logic in case the image has a strange
            // aspect ratio. For example, a panorama may have a much larger
            // width than height. In these cases the total pixels might still
            // end up being too large to fit comfortably in memory, so we should
            // be more aggressive with sample down the image (=larger
            // inSampleSize).

            final float totalPixels = width * height;

            // Anything more than 2x the requested pixels we'll sample down
            // further.
            final float totalReqPixelsCap = reqWidth * reqHeight * 2;

            while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }    

    public static Bitmap loadImageFromURL(String urlPath) {
        try {
            URL url = new URL(urlPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
            int rspCode = connection.getResponseCode();
            if (rspCode == HttpStatus.SC_OK) {
                //InputStream in = connection.getInputStream();
                Bitmap bitmap = null;
                BufferedInputStream in = new BufferedInputStream(url.openStream(), IMAGE_BUFFER_SIZE);
                byte[] data = getBytes(in);
                in.close();
                if (data != null) {
                    try {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        options.inSampleSize = calculateInSampleSize(options, MAX_REQUEST_WIDTH, MAX_REQUEST_HEIGHT);
                        options.inJustDecodeBounds = false;
                        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.i(TAG, "data == null");
                }

                connection.disconnect();                
                return bitmap;
            } else {
                connection.disconnect();
                Log.i(TAG, "rspCode = " + rspCode);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private class RefreshAsyncTask extends AsyncTask<String, Boolean, Boolean> {
        @Override
        protected Boolean doInBackground(String... arg0) {
            mContentPicBitmap = loadImageFromURL(arg0[0]);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (mContentPicBitmap != null) {
                initImageSetting(mContentPicBitmap);
                mContentPic.setImageBitmap(mContentPicBitmap);
            }
        }
    }    
}

解决方案

try this i have try with ur links it show me an image in imageview

BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage("http://218.240.46.38/img/201206/28/-980416187.jpeg", bmOptions);
imageview.setImageBitmap(bm);

where methos LoadImage is as given below

private Bitmap LoadImage(String URL, BitmapFactory.Options options){      
    Bitmap bitmap = null;
    InputStream in = null;      
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in, null, options);
        in.close();
    } catch (IOException e1) {

    }
   return bitmap;              
}


private InputStream OpenHttpConnection(String strURL) throws IOException {
     InputStream inputStream = null;
     URL url = new URL(strURL);
     URLConnection conn = url.openConnection();

     try{
        HttpURLConnection httpConn = (HttpURLConnection)conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
     } catch (Exception ex){

     }
     return inputStream;
}

这篇关于inputstream.read在下载大的图像时,没有响应(大小&GT; 300K)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆