簡體   English   中英

Android保存大位圖

[英]Android saving large bitmaps

我是android新手,我對如何處理Bitmaps感到困惑。

我想下載一個Bitmap ,它可能很大,然后將其保存到一個臨時內部文件中。 然后,我將稍后將此Bitmap繪制到Canvas

我當前的方法是1.下載輸入流2.復制流3.使用一個流使用bitmapFactory.options來確定邊界4.使用另一個流以樣本大小解碼完整的位圖

但是,我需要landscapeportrait版本,所以現在我將不得不執行兩次並保存兩個圖像。

或者-我見過人們使用bm.compress(Bitmap.CompressFormat.JPEG, 50, bos); 而是保存文件。 這將繞過解碼,而樣本量則直接從流中保存下來。 我猜想,當我繪制到Canvas時,我將使用矩陣縮放。

基本上,對於執行此任務的最佳方法,我感到困惑,哪種方法不太可能出現內存不足的情況,而更常用的方法是嗎?

干杯

  byte[] imagesByte = getLogoImage(Your url);

設置為imageview ...

 imgView.setImageBitmap(BitmapFactory.decodeByteArray( imagesByte,  0, imagesByte.length));

下載方法

 public static byte[] getLogoImage(String url){
            try {
                URL imageUrl = new URL(url);
                URLConnection ucon = imageUrl.openConnection();

                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

                ByteArrayBuffer baf = new ByteArrayBuffer(500);
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }

                return baf.toByteArray();
            } catch (Exception e) {
                Log.d("ImageManager", "Error: " + e.toString());
            }
            return null;
        }

在Android中,您必須注意內存有限,因此大圖像將無法容納在內存中,並且將出現OutOfMemory異常。

關鍵是,在將圖像保存到內部存儲器中之后,以顯示分辨率加載它:

首先下載圖像,這應該在UI線程之外完成,讓_url帶有圖像地址的URL實例和_file包含目標文件的String:

URLConnection conn = _url.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        boolean success = false; //track succesful operation

        if( _file != null)
        {
            try
            {
                FileOutputStream fos = new FileOutputStream(_file);
                byte data[] = new byte[4086]; //use 4086 bytes buffer

                int count = 0;
                while ((count = is.read(data)) != -1)
                {
                    fos.write(data, 0, count);//write de data
                }

                is.close();
                fos.flush();
                fos.close();

                int len =  conn.getContentLength();
                File f = new File( _file);//check fie length is correct
                if( len== f.length())
                {
                    success = true;
                }
                else
                {
                    //error downloading, delete de file
                    File tmp = new File( _file);
                    if( tmp.exists())
                    {
                        tmp.delete();
                    }
                }
            }catch (Exception e )
            {
                try
                {
                    e.printStackTrace();
                    //delete file with errors
                    File tmp = new File( _file);
                    if( tmp.exists())
                    {
                        tmp.delete();
                    }

                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
            finally
            {
                is.close();//cleanup

            }

然后,當您必須以所需的分辨率加載圖像時,此處的關鍵是使用BitmapFactory讀取位圖信息並獲取縮放的位圖:

public static Bitmap bitmapFromFile(int width, int height, String file)
{

    Bitmap bitmap = null;

    final BitmapFactory.Options options = new BitmapFactory.Options();

    if( height >0 && width > 0 ) {
        options.inJustDecodeBounds = true;//only read bitmap metadata
        BitmapFactory.decodeFile(file,options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, width, height);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

    }
    try
    {
        bitmap = BitmapFactory.decodeFile(file, options);//decode scaled bitmap
    }catch (Throwable t)
    {
        if( bitmap != null)
        {
            bitmap.recycle();//cleanup memory, very important!
        }
        return null;

    }
    return bitmap
}

最后一步是計算比例因子:

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) {

        final int halfHeight = height;
        final int halfWidth = width;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((couldShrink(halfWidth, reqWidth, inSampleSize)&&
                couldShrink(halfHeight,reqHeight, inSampleSize))
                //&&(halfHeight*halfWidth)/inSampleSize > maxsize)
                )
        {
            inSampleSize *= 2;
        }

    }

    return inSampleSize;
}
private static  boolean couldShrink ( int dimension, int req_dimension, int divider)
{
    int actual = dimension / divider;
    int next = dimension / (divider*2);

    int next_error = Math.abs(next - req_dimension);
    int actual_error = Math.abs(actual-req_dimension);

    return next > req_dimension ||
            (actual > req_dimension && (next_error < actual_error) )
            ;
}

那就是如果您想手工做的話,我建議您使用Picasso來處理圖像的下載,磁盤緩存和內存緩存:

要裝入的ImageView稱為image表示化背景( R.drawable.img_bg ),而下載:

Picasso.with(image.getContext())
            .load(url).placeholder(R.drawable.img_bg).fit()
                    .into(image, new Callback.EmptyCallback()
                    {
                        @Override
                        public void onSuccess()
                        {
                            holder.progress.setVisibility(View.GONE); //hide progress bar
                        }

                        @Override
                        public void onError()
                        {
                            holder.progress.setVisibility(View.GONE); //hide progress bar
                            //do whatever you design to show error
                        }
                    });

處理自己的位圖:

//first declare a target
_target = new Target()
    {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
        {
            //handle your bitmap (store it and use it on you canvas
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable)
        {
            //handle your fail state

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable)
        {//for example for drawing a placeholder while downloading
        }
    };

現在,您只需加載圖像並調整其大小:

Picasso.with(context).load(url).resize(192, 192).centerCrop().into(_target);

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM