有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从URL获取位图

我正在尝试从URL获取位图图像
(示例:https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png

但是connection.connect()行似乎有一个问题,我无法理解
我已允许在应用程序中访问internet

public static Bitmap getBitmapFromURL(String src) {
    HttpURLConnection connection = null;
    InputStream inputStream = null;
    try {
        URL url = new URL(src);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
    }
    return BitmapFactory.decodeStream(inputStream);
}  

共 (2) 个答案

  1. # 1 楼答案

    你可以用glide做一个简短的解决方案

        implementation "com.github.bumptech.glide:glide:4.11.0"
        annotationProcessor "com.github.bumptech.glide:compiler:4.11.0"
    
     try {
                            Bitmap bitmap = Glide
                                    .with(context)
                                    .asBitmap()
                                    .load(imageUrl)
                                    .submit()
                                    .get();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
    
  2. # 2 楼答案

    一般来说,网络连接应该在一个单独的线程中完成。你可以用AsyncTask来做这个。例如,这是有效的:

    ImageView imageView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_layout);
    
        imageView = (ImageView) findViewById(R.id.imageView);
        new LoadImage().execute("https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png");
    }
    
    private class LoadImage extends AsyncTask<String, Void, Bitmap>{
           @Override
           protected Bitmap doInBackground(String... strings) {
               Bitmap bitmap = null;
               try {
                   InputStream inputStream = new URL(strings[0]).openStream();
                   bitmap = BitmapFactory.decodeStream(inputStream);
               } catch (IOException e) {
                   e.printStackTrace();
               }
               return bitmap;
           }
    
           @Override
           protected void onPostExecute(Bitmap bitmap) {
               imageView.setImageBitmap(bitmap);
           }
       }