开发者

Why am I getting java.io.IOException: Mark has been invalidated?

开发者 https://www.devze.com 2023-03-13 17:11 出处:网络
I\'m trying to download imags from a url and then decode them. The problem is that I don\'t know how large are they and if I decode them right away, the app crashes with too-big images.

I'm trying to download imags from a url and then decode them. The problem is that I don't know how large are they and if I decode them right away, the app crashes with too-big images.

I'm doing the following and it works with most of the images but with some of them, it throws the java.io.IOException: Mark has been invalidated exception. It's not a matter of size because it happens with a 75KB or a 120KB image and not with a 20MB or 45KB image. Also the format is not important as it can happen either with a jpg or png image.

pis is an InputStream.

    Options opts = new BitmapFactory.Options();
    BufferedInputStream bis = new BufferedInputStream(pis);
    bis.mark(1024 * 1024);
    opts.inJustDecodeBounds = true;
    Bitmap bmImg=BitmapFactory.decodeStream(bis,null,opts);

    Log.e("optwidth",opts.outWidth+"");
    try {
        bis.reset();
        opts.inJustDecodeBounds = false;
        int ratio = opts.outWidth/800; 
        Log.e("ratio",String.valueOf(ratio));
        if (opts.outWidth>=800)opts.inSampleSize = ratio;

        return BitmapFactory.decodeStream(bis,null,opts);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackT开发者_JAVA百科race();
        return null;
    }


I think you want to decode large image. I did it by selecting gallery image.

File photos= new File("imageFilePath that you select");
Bitmap b = decodeFile(photos);

"decodeFile(photos)" function is used for decode large image. I think you need to get image .png or .jpg formet.

 private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale++;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

you can display it by using imageView.

ImageView img = (ImageView)findViewById(R.id.sdcardimage);
img.setImageBitmap(b);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号