【Android网络编程】获取网络图片,具有缓存功能

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013003052/article/details/49453341
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="查看网络图片" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:id="@+id/imageView"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载图片"
        android:id="@+id/button"
        android:layout_below="@+id/imageView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

package qindachang.internetdemo;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

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


public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private Button button;
    private MyThread myThread;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                myThread = new MyThread();
                myThread.start();
            }
        });
    }

    private void GetInternetImg() {
        //下载图片
        //1.确定网址
        String path = "http://img2.imgtn.bdimg.com/it/u=1031079800,2914158222&fm=21&gp=0.jpg";
        //②带缓存功能的读取
        File file = new File(getCacheDir(), getFileName(path));
        //如果缓存存在
        if (file.exists()) {
            //从缓存中读取图片
            bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            mHandler.sendEmptyMessage(0);

        } else {
            //2.把网址封装成url对象
            try {
                URL url = new URL(path);
                //3.获取客户端和服务器的连接对象,此时还没有建立连接,这时候还没有任何的网络交互
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                //4.对连接对象进行初始化
                //设置请求方法
                connection.setRequestMethod("GET");
                //设置连接超时时间
                connection.setConnectTimeout(5000);
                //设置读取超时
                connection.setReadTimeout(3000);
                //5.发送请求,与服务器建立连接,这段代码一旦执行,就会有网络交互了
                connection.connect();
                //如果响应码为200,说明请求成功
                if (connection.getResponseCode() == 200) {
                    //获取服务器响应头中的流,流里的数据就是客户端请求的数据
                    InputStream is = connection.getInputStream();
                    //从流里读数据,安卓有一个API可以从流里直接读取图片

                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = is.read(bytes)) != -1) {
                        fos.write(bytes, 0, len);
                    }
                    fos.close();
                    bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

                    //①从里读取数据,并构造成位图对象
//                bitmap = BitmapFactory.decodeStream(is);

                    mHandler.sendEmptyMessage(0);

                } else {
                    Toast.makeText(MainActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            imageView.setImageBitmap(bitmap);
            return false;
        }
    });

    private class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            GetInternetImg();
        }
    }

    private String getFileName(String path) {
        String[] name = path.split(",");
        return name[1];
    }
}

展开阅读全文

Android在ListView异步线程获取网络图片

04-12

根据目前服务器的设置,我需要先发一些信息,去获取图片的名称。然后再发信息到服务器,获取各个图片,我目前所有图片只会在最后一行循环刷新。。。这几天也试了很多方法,一直不成功。求指教了。rnrn[code=java]rnpublic class FileListAdapter extends BaseAdapter rn private Context context; // 运行上下文rn private List groupList = new ArrayList(); // 所有文件及文件夹rn // private List> childList = newrn // ArrayList>();//文件集合rn private LayoutInflater listContainer; // 视图容器rn private Files files;rn private boolean isOk;rn private boolean isFirst = true;rn private Handler handler;rn private ImageView imgfile;rn private ListItemView listItemView;rn rn public final class ListItemView // 自定义控件集合rn public Button downButton, friendButton, shareButton, renameButton;rn public Button deleteButton;rn private Button select_img;rn public ImageView img_isView;rn public TextView fileName, fileDate;rn rn rn public FileListAdapter(Context context, List groups) rn this.context = context;rn this.groupList = groups;rn listContainer = LayoutInflater.from(context);rn listItemView = new ListItemView();rn handler = new Handler() rn rn @Overridern public void handleMessage(Message msg) rn // TODO Auto-generated method stubrn switch (msg.what) rn rn case 2:rn notifyDataSetChanged();rn break;rn rn default:rn break;rn rn super.handleMessage(msg);rn rn rn ;rn rn rn rn @Overridern public int getCount() rn // TODO Auto-generated method stubrn return groupList.size();rn rn rn @Overridern public Object getItem(int position) rn // TODO Auto-generated method stubrn return groupList.get(position);rn rn rn @Overridern public long getItemId(int position) rn // TODO Auto-generated method stubrn return position;rn rn rn @Overridern public View getView(int position, View convertView, ViewGroup parent) rn // TODO Auto-generated method stubrn rn if (convertView == null) rn convertView = listContainer.inflate(R.layout.item_filelist, null);rn rn imgfile = (ImageView) convertView.findViewById(R.id.img_fileimg);rn // 初始化绑定控件rn listItemView.deleteButton = (Button) convertViewrn .findViewById(R.id.btn_delete);rn listItemView.downButton = (Button) convertViewrn .findViewById(R.id.btn_download);rn listItemView.friendButton = (Button) convertViewrn .findViewById(R.id.btn_friend);rn listItemView.renameButton = (Button) convertViewrn .findViewById(R.id.btn_rename);rn listItemView.shareButton = (Button) convertViewrn .findViewById(R.id.btn_share);rn listItemView.fileName = (TextView) convertViewrn .findViewById(R.id.txt_fileName);rn listItemView.fileDate = (TextView) convertViewrn .findViewById(R.id.txt_fileDate);rn listItemView.select_img = (Button) convertViewrn .findViewById(R.id.btn_select);rn rn listItemView.img_isView = (ImageView) convertViewrn .findViewById(R.id.img_checkimg);rn rn // 进行初始化赋值rn initData(convertView, position);rn setListener(convertView, position, parent);rn rn return convertView;rn rn rn private void setListener(final View convertView, final int position,rn final ViewGroup parent) rn // TODO Auto-generated method stubrn final Files Cur_file = groupList.get(position);rn final String Cur_fileName = groupList.get(position).getFileName();rn rn rn rn rn private void initData(View convertView, final int position) rn // TODO Auto-generated method stubrn Files files = new Files();rn files = groupList.get(position);rn listItemView.fileName.setText(files.getFileName());rn rn // 判断是文件rn if (files.isFile()) rn String fileType = files.getFileName().substring(rn files.getFileName().lastIndexOf("."),rn files.getFileName().length());rn listItemView.fileDate.setText(files.getLastModified() + " "rn + files.getLength());rn listItemView.downButton.setText("下载");rn listItemView.downButton.setTag("下载");rn if (fileType.equals(".jpg") || fileType.equals(".png")rn || fileType.equals(".gif") || fileType.equals(".Jpeg")rn || fileType.equals(".bmp")) rn//我现在就是要在这里,如果是图片。我就要去服务器获取文件名,文件名的获取是通过rn//HttpCookieUtils httpCookieUtils = new HttpCookieUtils(); rn//httpCookieUtils.preview( groupList.get(position).getPath(),rn// "40", "40"); rn//这个返回的是一个字符串,就是文件名。然后再设置缩略图,但是一直不成功,只会在最后一行循环刷新图片。而且线程一直在跑rn//下面注释的都是我之前写的代码rn rn /*rn * new Thread() rn * rn * @Override public void run() // TODO Auto-generated methodrn * stub HttpCookieUtils httpCookieUtils = new HttpCookieUtils();rn * String msg = null; Bitmap bitmap = null; try msg =rn * httpCookieUtils.preview( groupList.get(position).getPath(),rn * "40", "40"); bitmap = BitmapUtilsrn * .getHttpBitmap(Constants.API_HOST + Constants.API_SHOW +rn * msg); catch (NotLoginException e) // TODO Auto-generatedrn * catch block e.printStackTrace(); catch (IOException e) //rn * TODO Auto-generated catch block e.printStackTrace(); rn * Message m = handler.obtainMessage(1, 1, 1, bitmap);rn * handler.sendMessage(m); super.run(); rn * rn * rn * .start();rn */rn rn rn rn else rn listItemView.fileDate.setText(files.getLastModified());rn listItemView.downButton.setText("打开");rn listItemView.downButton.setTag("打开");rn groupList.get(position).setFileImg("file");rn imgfile.setBackgroundResource(R.drawable.img_filelist);rn rn rnrn[/code] 论坛

android获取网络图片并显示的问题

05-20

我在网上看了一些解析图片的代码,然后用一些网站的图片进行测试,但是当解析我的网站的图片的时候,就直接报错,我个人认为应该是我的网站的图片太大的缘故,然后我按照网上给的图片压缩的方法进行尝试,但是发现没有什么效果,不知道是什么原因,恳请各位指教。少都不说了直接上代码:rnprotected void onCreate(Bundle savedInstanceState) rnsuper.onCreate(savedInstanceState);rnsetContentView(R.layout.activity_main);rnrnrnrnbutton = (Button)findViewById(R.id.buttonId);rnbutton.setOnClickListener(new OnClickListener() rnrn@Overridernpublic void onClick(View v) rnmyAsyncTask = new MyAsyncTask();rnmyAsyncTask.execute();rnrn);rnimageView=(ImageView)findViewById(R.id.imageViewId);rnrnrn//下载图片rnpublic void loadImageFromUrl() rnURL m;rn// String url=“http://news.ucas.ac.cn/Content/Upload/2014/5/315.jpg”//这个链接是网站需要的图片rnString url="http:////imgsrc.baidu.com/forum/pic/item/0a6d462c11dfa9eca10597e560d0f703908fc15c.jpg"// 测试用的图片rnInputStream i = null;rnBufferedInputStream bis = null;rnByteArrayOutputStream outStream = new ByteArrayOutputStream(); rntry rnm = new URL(url);rni = (InputStream) m.getContent();rnbis = new BufferedInputStream(i,1024 * 8);rnrnrnBitmapFactory.Options options = new BitmapFactory.Options();rnoptions.inJustDecodeBounds = true; rn// 从输入流读取数据 rnbyte[] data = StreamTool.read(bis);rnBitmapFactory.decodeByteArray(data, 0, data.length, options); rnint w = options.outWidth; rnint h = options.outHeight; rn// 从服务器端获取的图片大小为:80x120 rn// 我们想要的图片大小为:40x40 rn// 缩放比:120/40 = 3,也就是说我们要的图片大小为原图的1/3 rnrn// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 rnint ratio = 1; // 默认为不缩放 rnif (w >= h && w > width) rnratio = (int) (w / width); rn else if (w < h && h > height) rnratio = (int) (h / height); rn rnrnif (ratio <= 0) rnratio = 1; rn rnrnSystem.out.println("图片的缩放比例值ratio = " + ratio); rnrnoptions.inJustDecodeBounds = false; rn// 属性值inSampleSize表示缩略图大小为原始图片大小的几分之一,即如果这个值为2, rn// 则取出的缩略图的宽和高都是原始图片的1/2,图片大小就为原始大小的1/4。 rnoptions.inSampleSize = ratio; rnbitmap = BitmapFactory.decodeByteArray(data, 0, data.length); rn// 图片质量默认值为100,表示不压缩 rnint quality = 10; rn// PNG是无损的,将会忽略质量设置。因此,这里设置为JPEG rnbitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream); rn// 判断压缩后图片的大小是否大于100KB,大于则继续压缩 rnwhile (outStream.toByteArray().length / 1024 > 100) rnoutStream.reset(); rnrn// 压缩quality%,把压缩后的数据存放到baos中 rnbitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream); rnquality -= 10; rn rnSystem.out.println("quality = " + quality); rnrnbyte[] data01 = outStream.toByteArray(); rnbitmap01 = BitmapFactory.decodeByteArray(data, 0, data.length);rn catch (IOException e) rn// TODO Auto-generated catch blockrne.printStackTrace();rn rnSystem.out.println(bitmap01.getWidth()+"::"+bitmap01.getHeight());rnrnrnrnprivate Bitmap getBitmap()rnrnreturn bitmap01;rnrn//开启新的线程下载图片 rnprivate class MyAsyncTask extends AsyncTaskrnrn@Overridernprotected Void doInBackground(Object... params) rnloadImageFromUrl();rnreturn null;rnrnrnrn@Overridernprotected void onPostExecute(Void result) rnimageView.setImageBitmap(getBitmap());rn//imageView.invalidate();rnrnrnrnrnrnrnrn不清楚是啥原因,望知道的大神告知。。。万分感谢 论坛

没有更多推荐了,返回首页