从存储在 sdcard 上的 png 文件创建位图 (Android)

2023-11-29

我尝试从 SD 卡上存储的 Png 文件创建位图,然后在 imageView 中设置该位图。 但它不起作用。

这是代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import com.pxr.tutorial.xmltest.R;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;

public class Getbackground {
    URL url;

    public static long downloadFile(URL url2) {
    try {

        URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
        InputStream input = url.openStream();{
        try {

            File fileOnSD=Environment.getExternalStorageDirectory();    
            String storagePath = fileOnSD.getAbsolutePath();
            OutputStream output = new FileOutputStream (storagePath + "/oranjelanbg.png");
                try {

                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, bytesRead);
                    }
                    } finally {
            output.flush();
            output.close();
//----------------------------------------------------------------------------------------------------------
            Bitmap BckGrnd = BitmapFactory.decodeFile(storagePath + "/oranjelanbg.png");
            ImageView BackGround=(ImageView)findViewById(R.id.imageView1);
            BackGround.setImageBitmap(BckGrnd);
//----------------------------------------------------------=-----------------------------------------------
            }
            } catch (IOException e) {
            throw new RuntimeException(e);
    } finally {
        try {
            input.close();
            } catch (IOException e) {
            throw new RuntimeException(e);
     }
   }    
 }    
        } catch (MalformedURLException ex) {
         throw new RuntimeException(ex);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

        return 0;
    }
//-----------------------------------------------------------------------------------------
    private static ImageView findViewById(int imageview1) {
        // TODO Auto-generated method stub
        return null;
    }
//-----------------------------------------------------------------------------------------
}

文件确实成功加载到 SD 卡上,但我似乎无法在视图中获取 img。


你不能..

ImageView BackGround=(ImageView)findViewById(R.id.imageView1);
BackGround.setImageBitmap(BckGrnd);

怎样才能得到参考ImageView在非活动课上Getbackground?

您只能更新 MainUI 线程中的 UI 组件,如果它位于非 Activity 类中,则仅使用该调用活动类的引用(上下文)。

因此,在 Getbackground 完成后将此代码放入您的 Activity 类中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从存储在 sdcard 上的 png 文件创建位图 (Android) 的相关文章

随机推荐