android网络图片查看器

package com.itheima.netimageviewer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.Resources.Theme;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    protected static final int LOAD_IMAGE = 1;
    protected static final int LOAD_ERROR = 2;
    // 服务器所有图片的路径
    private List<String> paths;
    private ImageView iv;
    /**
     * 当前的位置
     */
    private int currentPosition = 0;

    //1.创建一个消息处理器
    private Handler handler = new Handler(){
        //3.处理消息
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case LOAD_IMAGE:
                Bitmap bitmap = (Bitmap) msg.obj;
                iv.setImageBitmap(bitmap);
                break;

            case LOAD_ERROR:
                Toast.makeText(getApplicationContext(), (String)msg.obj, 0).show();
                break;
            }

        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv);
        // 1.连接服务器 获取所有的图片的目录信息
        loadAllImagePath(); 

    }

    /**
     * 开始加载图标,在从服务器获取完毕资源路径之后执行
     */
    private void beginLoadImage() {
        // TODO:把每个图片的路径获取出来, 通过路径加载图片.
        try {
            paths = new ArrayList<String>();
            File file = new File(getCacheDir(), "info.txt");
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String line;
            while ((line = br.readLine()) != null) {
                paths.add(line);
            }
            fis.close();
            // 2.加载图片资源
            loadImageByPath(paths.get(currentPosition));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 通过路径获取图片资源
     *
     * @param path
     *            图片的路径
     * @return
     */
    private void loadImageByPath(final String path) {
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(2000);
                    // 判断缓存是否存在,如果存在就那缓存图片,如果不存在才去获取服务器的资源
                    File file = new File(getCacheDir(), path.replace("/", "")
                            + ".jpg");
                    if (file.exists() && file.length() > 0) {
                        System.out.println("通过缓存把图片资源获取出来....");
                        // 缓存存在
                        //iv.setImageBitmap( BitmapFactory.decodeFile(file.getAbsolutePath()));
                        //2.子线程想去更新ui,发送消息
                        Message msg = Message.obtain();
                        msg.what = LOAD_IMAGE;
                        msg.obj = BitmapFactory.decodeFile(file.getAbsolutePath());
                        handler.sendMessage(msg);
                    } else {
                        System.out.println("通过访问网络把图片资源获取出来....");
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        conn.setRequestMethod("GET");
                        int code = conn.getResponseCode();
                        if (code == 200) {
                            InputStream is = conn.getInputStream();
                            // 内存中的图片
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            // 如果图片被下载完毕了,应该把图片缓存起来.
                            // CompressFormat.JPEG 压缩的方式 png jpg
                            // 100 压缩比例 100 无损压缩
                            // stream 把图片写入到哪个缓存流里面
                            FileOutputStream stream = new FileOutputStream(file);
                            bitmap.compress(CompressFormat.JPEG, 100, stream);
                            stream.close();
                            is.close();
                            Message msg = Message.obtain();
                            msg.obj = bitmap;
                            msg.what = LOAD_IMAGE;
                            handler.sendMessage(msg);
                            //iv.setImageBitmap(bitmap);
                        } else {
                            //Toast.makeText(MainActivity.this, "获取失败", 0).show();
                            Message msg = Message.obtain();
                            msg.what = LOAD_ERROR;
                            msg.obj = "获取失败";
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "获取失败", 0).show();
                    Message msg = Message.obtain();
                    msg.what = LOAD_ERROR;
                    msg.obj = "获取失败";
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }

    /**
     * 获取全部图片资源的路径
     */
    private void loadAllImagePath() {
        new Thread() {
            public void run() {
                // 浏览器发送一个get请求就可以把服务器的数据获取出来.
                // 用代码模拟一个http的get请求
                try {
                    // 1.得到服务器资源的路径
                    URL url = new URL("http://192.168.1.109:8080/img/gaga.html");
                    // 2.通过这个路径打开浏览器的连接.
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();// ftp
                                                // http
                                                // https
                                                // rtsp
                    // 3.设置请求方式为get请求
                    conn.setRequestMethod("GET");// 注意get只能用大写 不支持小写
                    // 为了有一个更好的用户ui提醒,获取服务器的返回状态码
                    int code = conn.getResponseCode();// 200 ok 404资源没有找到 503
                                                        // 服务器内部错误
                    if (code == 200) {
                        // 4.获取服务器的返回的流
                        InputStream is = conn.getInputStream();
                        File file = new File(getCacheDir(), "info.txt");
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                        is.close();
                        fos.close();
                        beginLoadImage();
                    } else if (code == 404) {
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        msg.obj = "获取失败,资源没有找到";
                        handler.sendMessage(msg);
                        //Toast.makeText(MainActivity.this, "获取失败,资源没有找到", 0).show();
                    } else {
                        //Toast.makeText(MainActivity.this, "服务器异常", 0).show();
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        msg.obj = "服务器异常";
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //Toast.makeText(MainActivity.this, "获取失败", 0).show();
                    Message msg = Message.obtain();
                    msg.what = LOAD_ERROR;
                    msg.obj = "获取失败";
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }

    /**
     * 上一张
     *
     * @param view
     */
    public void pre(View view) {
        currentPosition--;
        if (currentPosition < 0) {
            currentPosition = paths.size() - 1;
        }
        loadImageByPath(paths.get(currentPosition));

    }

    /**
     * 下一张
     *
     * @param view
     */
    public void next(View view) {
        currentPosition++;
        if (currentPosition == paths.size()) {
            currentPosition = 0;
        }
        loadImageByPath(paths.get(currentPosition));

    }

}

添加权限

<uses-permission android:name="android.permission.INTERNET"/>
时间: 2024-07-28 17:13:49

android网络图片查看器的相关文章

[android] 网络图片查看器

界面布局LinerLayout线性布局,ImageView控件,EditText控件 hint属性提示信息,Button控件. Android:layout_weight=””属性,权重,只有控件的宽度和高度为0的时候才代表权重,否则它代表渲染的优先级,值越大优先级越低,默认是0,先渲染其他控件 singleLine属性 单行 业务逻辑,获取EditText的值放到ImageView里,实质上是http的get请求 获取EditText对象,通过findViewById() 获取值,通过调用Ed

android 网络_网络图片查看器

xml <?xml version="1.0"?> -<LinearLayout tools:context=".MainActivity" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingLeft="

无废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4)

1.内容观察者ContentObserver 如果ContentProvider的访问者需要知道ContentProvider中的数据发生了变化,可以在ContentProvider 发生数据变化时调用getContentResolver().notifyChange(uri, null)来通知注册在此URI上的访问者,例子如下: private static final Uri URI = Uri.parse("content://person.db"); public class

【黑马Android】(05)短信/查询和添加/内容观察者使用/子线程网络图片查看器和Handler消息处理器/html查看器/使用HttpURLConnection采用Post方式请求数据/开源项目

备份短信和添加短信 操作系统短信的uri: content://sms/ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.itheima28.backupsms" android:versionCode="1

(十二)网络图片查看器(注释更全面)

(一)android:layout_weight 在不同情况下的意义. 当 android:layout_width  和 android:layout_height都不为0的时候,android:layout_weight代表的是控件渲染的优先级,值越大,渲染的优先级越低.默认android:layout_weight=0. 当 android:layout_width  或 android:layout_height为0的时候,android:layout_weight才代表权重,值越大,权

android---利用android-async-http开源项目实现网络图片查看器

1.   导包:导入android-async-http开源项目的最新版本的包 2.简单的搭建一个网络图片查看器的界面 相关的界面搭建代码: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent

Android图片查看器(图片可移动、缩放)

要实现图片在手指点击后移动和缩放有好几种方法,在这里是通过onTouch来实现的. 实例代码如下: 首先是在View中有一个ImageView <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_paren

从零封装一个Android大图查看器

背景: 大图查看器是许多app的常用功能,主要使用场景是用户点击图片,然后启动一个新界面来展示图片的完整尺寸,并能通过手势移动图片以及放大缩小.当然,上面说的是最基本的功能,实际使用中还要包括:如果是本地图片应该可以移除,如果是网络图片,应提供一个保存到本地的功能等. 本文为什么叫封装一个大图查看器,而不是叫做编写一个大图查看器呢?因为大图查看器的最核心功能,展示图片以及手势操控我们使用了一个开源库来完成,这个开源库叫做subsampling-scale-image-view,这个开源库非常靠谱

Android 网络图片查看显示的实现方法

效果图如下: 界面中有三个控件,一个EditText,一个Button,一个ImageView 1.下面是具体布局文件 <EditText android:id="@+id/picturepagh" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello_world" />