如何从图库动态卸载图像?

2024-06-02

我有自定义 ImageView:

public class ShadowedImageView extends ImageView {

private Paint mPaint;
public Bitmap bitmap = null;
private Bitmap tempBitmap;
private Bitmap thumb;
private Bitmap image;
public float shadowRadius = 2f;
public float shadowDx = 1f;
public float shadowDy = 1f;
public int shadowColor = Color.BLACK;
public int scale = 1;
public int requiredWidth = 768;
public int requiredHeight = 1024;
public int loaded = 0;

public ShadowedImageView(Context context) {
    super(context);
    setShadow();
    loaded = 0;
}

public ShadowedImageView(Context context, AttributeSet attrs){
    super(context, attrs);
    setShadow();
    loaded = 0;
}

public void setShadow(){
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setShadowLayer(shadowRadius, shadowDx, shadowDy, shadowColor);
    Resources res = getResources();
    Drawable drawable = res.getDrawable(R.drawable.pl);
    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pl);
    setImageDrawable(drawable);
}

public void refreshShadow(){
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setShadowLayer(shadowRadius, shadowDx, shadowDy, shadowColor);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
}

@Override
protected void onMeasure(int w, int h) {
    super.onMeasure(w,h);

    int mH, mW;
    mW = getSuggestedMinimumWidth() < getMeasuredWidth()? getMeasuredWidth() : getSuggestedMinimumWidth();
    mH = getSuggestedMinimumHeight() < getMeasuredHeight()? getMeasuredHeight() : getSuggestedMinimumHeight();
    setMeasuredDimension(mW + 5, mH + 5);

}

public void downloadThumb(final Publication pub){
    OnClickListener theCommonListener = new OnClickListener(){
        @Override
        public void onClick(View v) {               
            Intent intent = new Intent(v.getContext(), PublicationReader.class);
            intent.putExtra("pubUrl", pub.publicationUrl);
            intent.putExtra("pubPages", pub.publicationPages);
            intent.putExtra("pubId", pub.id);

            v.getContext().startActivity(intent);
        }
    };
    this.setOnClickListener(theCommonListener);
    download(pub.thumbImageUrl);
}

public void download(String fileUrl){
    downloadTask t = new downloadTask();
    t.loadData(fileUrl, this);
    t.execute();
}

private class downloadTask extends AsyncTask<String, Void, Long> {
    String fileUrl;
    ShadowedImageView imView;

    public void loadData(String u, ShadowedImageView i) {
        fileUrl = u;
        imView = i;
    }

    @Override
    protected Long doInBackground(String... params) {
        try{
            Bitmap bmImg = null;
            URL myFileUrl = null;
            try {
                if(fileUrl!=null){
                    myFileUrl= new URL(fileUrl);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                if(myFileUrl!=null){
                    HttpURLConnection conn=(HttpURLConnection)myFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    decodeStream(is);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Long result){
        setImageBitmap(bitmap);
        invalidate();

    }
}

private void decodeStream(InputStream is){
    try {
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        bitmap = BitmapFactory.decodeStream(is, null, o2);
        refreshShadow();
        loaded = 1;
        invalidate();
    } catch (Exception e) {
        e.printStackTrace();
    }
}   
}

和画廊的适配器:

public class AddImgAdp extends BaseAdapter {
    int GalItemBg;
    private Context cont;

    private ShadowedImageView[] Imgid;

    public AddImgAdp(Context c) {
        Imgid = pagesArray;
        cont = c;
        TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
        GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
        typArray.recycle();
    }

    public int getCount() {
        return pagesArray.length;
    }

    public Object getItem(int position) {
        return pagesArray[position];
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ShadowedImageView imgView = pagesArray[position];
        pagesArray[position].scale = 1;
        pagesArray[position].download(URL_TO_LOAD_IMAGE);

        DisplayMetrics dm = new DisplayMetrics();

        imgView.setScaleType(ImageView.ScaleType.FIT_XY);
        imgView.setBackgroundResource(GalItemBg);
        return imgView;
    }
}

图像很大,当应用程序读取大量图像时,我就会内存不足。我想从内存中删除所有不可见的图像,例如:

                +-------------+
                |    screen   |
[1] [2] [3] [4] | [5] [6] [7] | [8] [9] [10]
                |             |
                +-------------+

图 1-3 和 9-10 是不必要的 - 所以我想释放内存。怎么做?


我遇到了同样的问题,您需要做的是创建与图库一起使用的自定义适配器,并使用 getView 函数回收位图:

public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(this.myContext);
        Bitmap tempBitmap = null;

        //Check if my PhotoList at this position is not null...

        //Free previous photos
        if ((position-3)>=0 && listBitmap.size()-3 >=0 && listBitmap(position-3) != null){
            //Here is to free for 1 photo, you can free more ... (3 in your case)
            listBitmap(position-3).recycle();
            listBitmap(position-3).setBitmap(null);
            Log.w(TAG, "Delete Photo-3");
        }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从图库动态卸载图像? 的相关文章

随机推荐

  • 为什么我无法对自定义属性(又名 CSS 变量)进行动画处理?

    看这个动画 金色 div 有一个自定义属性动画的动画 keyframes roll o 1动画 o 这是分步动画的 银色 div 有一个动画 其中normal属性是动画的 keyframes roll o 2动画left 这会持续动画 为什
  • 如何向开关对象添加/更改波纹效果

    下面是我自定义的开关 红圈是默认的波纹效果 我发现设置一个波纹可绘制作为开关的背景 控制波纹的颜色
  • 如何在MUI GridList中实现图块的水平滚动?

    这是我的 JS 页面 我需要在其中实现GridList组件显示多个图块 并且在列表大小超出屏幕限制后可水平滚动 import React useState from react import Header from common heade
  • 如何使用 jenkins pipeline 共享库定义全局变量或常量?

    虽然我能够定义方法 但使用 Jenkins 共享库定义变量似乎是迄今为止尚未解决的任务 I added vars True groovy有了这个身体 def call return true 现在在 Jenkinsfile 中 我尝试测试它
  • FastText - 由于 C++ 扩展未能分配内存,无法加载 model.bin

    我正在尝试使用 FastText Python APIhttps pypi python org pypi fasttext https pypi python org pypi fasttext虽然 据我所知 此 API 无法加载较新的
  • C#6 中的长字符串插值行

    我发现 虽然字符串插值在应用于现有代码库的字符串 Format 调用时非常好 但考虑到通常首选的列限制 字符串对于单行来说很快就会变得太长 特别是当被插值的表达式很复杂时 使用格式字符串 您将获得一个可以拆分为多行的变量列表 var str
  • PHP + MySQL 队列

    我需要一个充当队列的简单表 我的 MySQL 服务器限制是我不能使用 InnoDB 表 只能使用 MyISAM 客户 工人将同时工作 他们每次都需要接受不同的工作 我的想法是执行以下操作 伪代码 job lt SELECT FROM que
  • 在单元测试中运行 Airflow 1.9 的测试 Dag

    我已经实现了运行单个 dag 的测试用例 但它似乎在 1 9 中不起作用 可能是由于气流 1 8 中引入了更严格的池 我正在尝试运行以下测试用例 from airflow import DAG from airflow operators
  • 析构函数中的异步操作

    尝试在类析构函数中运行异步操作失败 这是代码 public class Executor public static void Main var c1 new Class1 c1 DoSomething public class Class
  • 未知的表引擎“InnoDB”

    最近 我发现如果我有好的硬件 我可以最大限度地提高 mysql 的性能 由于我一直在使用 InnoDB 所以我在 my ini 中添加了额外的配置 以下是新添加的配置 innodb data file path ibdata1 10M au
  • mysql:返回右侧第一个出现的子字符串? (子字符串?!)

    有没有办法返回sql中字符串右侧第一次出现的空格 我想你正在寻找类似的东西SUBSTRING INDEX http dev mysql com doc refman 5 0 en string functions html function
  • 在 asp.net MVC 中使用活动目录进行身份验证

    我想使用活动目录对我的 asp net mvc 项目中的用户进行身份验证 在网上冲浪了几个小时后 我没有找到任何对我有用的东西 我已经看到了所有结果 但什么也没有 我尝试按照许多帖子的建议编辑我的 web config 如果有人可以帮助我提
  • 搜索实体的所有字段

    我正在尝试在客户数据库上实现 多功能框 类型的搜索 其中单个查询应尝试匹配客户的任何属性 这是一些示例数据来说明我想要实现的目标 FirstName LastName PhoneNumber ZipCode Mary Jane 12345
  • 在 pip.conf 中指定多个可信主机

    这是我尝试在我的中设置的 etc pip conf global trusted host pypi org files pythonhosted org 但是 它无法正常工作 参考 https pip pypa io en stable
  • 将全局标题添加到 Plots.jl 子图

    我想使用 Plots jl 向一组子图添加全局标题 理想情况下 我会做类似的事情 using Plots pyplot plot rand 10 2 plot title Main title title A B layout 2 但是 根
  • 安全地评估简单的数学

    我想知道是否有一种安全的方法来评估数学 例如 2 2 10000 12000 10000 20 2 2 40 20 23 12 无需使用eval 因为输入可以来自任何用户 我需要实现的只是整数的加法和减法 是否有任何已经存在的代码片段 或者
  • Google Apps OpenID 网址

    Problem 我的组织 ExampleFooBar 使用 Google Apps 在我们的网站上我想要 启用 OpenID 单点登录 如 StackOverflow 但只允许 examplefoobar com 用于登录的电子邮件地址 我
  • tomcat-maven-plugin 使用 Tomcat 7 - tomcat:deploy 有效,tomcat:undeploy 无效

    我有一个 tomcat deploy 的工作配置 但是当我取消部署 WAR 时 出现以下错误 这让我很困惑 INFO Scanning for projects WARNING WARNING Some problems were enco
  • ValueError:无法插入 ID,已存在

    我有这个数据 ID TIME 1 2 1 4 1 2 2 3 我想按以下方式对数据进行分组ID并计算每组的平均时间和规模 ID MEAN TIME COUNT 1 2 67 3 2 3 00 1 如果我运行此代码 则会收到错误 ValueE
  • 如何从图库动态卸载图像?

    我有自定义 ImageView public class ShadowedImageView extends ImageView private Paint mPaint public Bitmap bitmap null private