FetchBitmapTask

/*
 * Copyright (C) 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.libraries.cast.companionlibrary.utils;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * An AsyncTask to fetch an image over HTTP and scale it to the desired size. Clients need to extend
 * this and implement their own {@code onPostExecute(Bitmap bitmap)} method. It provides a uniform
 * treatment of ThreadPool across various versions of Android.
 */
public abstract class FetchBitmapTask extends AsyncTask<Uri, Void, Bitmap> {
    private final int mPreferredWidth;
    private final int mPreferredHeight;
    private final boolean mAllowedToScale;

    /**
     * Constructs a new FetchBitmapTask that will do in-sampling and scaling, if needed.
     *
     * @param preferredWidth The preferred image width.
     * @param preferredHeight The preferred image height.
     * @param allowedToScale If {@code true}, the resulting bitmap will be scaled to match the
     * preferred dimensions while keeping the aspect ratio. Otherwise, no additional scaling will
     * be performed.
     */
    public FetchBitmapTask(int preferredWidth, int preferredHeight, boolean allowedToScale) {
        mPreferredWidth = preferredWidth;
        mPreferredHeight = preferredHeight;
        mAllowedToScale = allowedToScale;
    }

    /**
     * Constructs a new FetchBitmapTask that will do in-sampling but no scaling.
     *
     * @param preferredWidth The preferred image width.
     * @param preferredHeight The preferred image height.
     *
     * @see FetchBitmapTask#FetchBitmapTask(int, int, boolean)
     */
    public FetchBitmapTask(int preferredWidth, int preferredHeight) {
        this(preferredWidth, preferredHeight, false);
    }

    /**
     * Constructs a new FetchBitmapTask. No scaling or in-sampling will be performed if you use this
     * constructor.
     *
     * @see FetchBitmapTask#FetchBitmapTask(int, int)
     * @see FetchBitmapTask#FetchBitmapTask(int, int, boolean)
     */
    public FetchBitmapTask() {
        this(0, 0);
    }

    @Override
    protected Bitmap doInBackground(Uri... uris) {
        if (uris.length != 1 || uris[0] == null) {
            return null;
        }

        Bitmap bitmap = null;
        URL url;
        try {
            url = new URL(uris[0].toString());
        } catch (MalformedURLException e) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 1;
        if ((mPreferredWidth > 0) && (mPreferredHeight > 0)) {
            // This is done to do appropriate resampling when the image is too large for the
            // desired target size; instead of downloading the original image and resizing that
            // (which can run into OOM exception), we find an appropriate in-sample-size and
            // only adjust the options to download the resized version.
            Point originalSize = calculateOriginalDimensions(url);
            if (originalSize.x > 0 && originalSize.y > 0) {
                options.inSampleSize = calculateInSampleSize(originalSize.x, originalSize.y,
                        mPreferredWidth, mPreferredHeight);
            }
        }
        HttpURLConnection urlConnection = null;
        InputStream stream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);

            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = new BufferedInputStream(urlConnection.getInputStream());
                bitmap = BitmapFactory.decodeStream(stream, null, options);
                if ((mPreferredWidth > 0) && (mPreferredHeight > 0) && mAllowedToScale) {
                    bitmap = scaleBitmap(bitmap);
                }
            }
        } catch (IOException e) { /* ignore */
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) { /* ignore */
                }
            }
        }

        return bitmap;
    }

    /**
     * Executes the task.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void execute(Uri uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, uri);
        } else {
            execute(new Uri[] {uri});
        }
    }

    /*
     * Scales the bitmap to the preferred width and height.
     *
     * @param bitmap The bitmap to scale.
     * @return The scaled bitmap.
     */
    private Bitmap scaleBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // Calculate deltas.
        int dw = width - mPreferredWidth;
        int dh = height - mPreferredHeight;

        if ((dw == 0) && (dh == 0)) {
            return bitmap;
        }

        float scaleWidth = (float) mPreferredWidth / width;
        float scaleHeight = (float) mPreferredHeight / height;
        float scaleFactor = Math.min(scaleHeight, scaleWidth);

        int finalWidth = (int) ((width * scaleFactor) + 0.5f);
        int finalHeight = (int) ((height * scaleFactor) + 0.5f);

        return Bitmap.createScaledBitmap(bitmap, finalWidth, finalHeight, false);
    }

    /**
     * Returns the original size of the image.
     */
    private Point calculateOriginalDimensions(URL url) {
        int inSampleSize = 0;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = inSampleSize;
        HttpURLConnection connection = null;
        InputStream stream = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            stream = connection.getInputStream();
            BitmapFactory.decodeStream(stream, null, options);
            return new Point(options.outWidth, options.outHeight);
        } catch (IOException e) {
             /* ignore */
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) { /* ignore */
                }
            }
        }
        return new Point(0, 0);
    }

    /**
     * Find the appropriate in-sample-size (as an inverse power of 2) to help reduce the size of
     * downloaded image.
     */
    private int calculateInSampleSize(int originalWidth, int originalHeight,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        int inSampleSize = 1;

        if (originalHeight > reqHeight || originalWidth > reqWidth) {

            final int halfHeight = originalHeight / 2;
            final int halfWidth = originalWidth / 2;

            // 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 ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容

  • 你还在为手机上分享图纸而烦恼吗? 你还在苦苦寻找简单的分享技巧吗? 不用找了,这就告诉你! 1、打开“CAD手机看...
    小可_aa09阅读 472评论 0 0
  • print 语句 学习编程,你最急于什么?答案肯定是上手写点小程序,这样也能满足自己小小的学习成就感。那么,pri...
    LP帅气的昵称阅读 662评论 0 0
  • 两天没写东西了,从学校搬来新的实习点,生活节奏全被打乱。宿舍没桌子看书,没wifi听音频,啥都做不了,五个人索性跑...
    后后先在想什么阅读 254评论 1 1
  • 这两天,又是一个亲友的离去!虽说早已经历了好多的离别,心里还是淡淡的忧伤!离去便是往生,去往极乐世界,那里便是天堂...
    60c5ad9c19ea阅读 571评论 0 1