频道栏目
首页 > 程序开发 > 移动开发 > Android > 正文
Android开发图片相关知识解析
2017-12-07 10:38:39      个评论    来源:kansas_lh的博客  
收藏   我要投稿

Android开发图片相关知识解析,用到5个类 向服务器发请求获取图片JSON加载解析到ListView里显示。
Util获取Json
NewsAdapter作为listview适配器
ImageLoader 这个类神奇了 具体功能看代码吧.. 几句话说不完
SelectPictureHandler解析Json (多线程)
PictureActivity 综合内容 进行显示

用到了cache缓存,从Url读取图片信息,再异步加载出来

理解多线程的概念,我在实际操作的时候一个大棚id死活传不进去,后来是忘记了构造函数里有

注:代码有很强的环境特性,用的话需要修改较多

Util类

public class Util {
    //读取流中的数据
    public static byte[] getByte(InputStream is)throws Exception {
        ByteArrayOutputStream output=new ByteArrayOutputStream();
        byte[] buff=new byte[1024];
        int len=0;
        while((len=is.read(buff))!=-1)
        {
            output.write(buff, 0, len);
        }
        return output.toByteArray();
    }
    //发送post请求并接受返回信息
    public static String sendPostRequest(String path, Map params, String encoding) throws IOException {
        String result="";
        List pairs=new ArrayList();
        if(pairs!=null)
        {
            for(Map.Entryentry:params.entrySet()){
                pairs.add(new BasicNameValuePair(entry.getKey(),  entry.getValue()));
            }
        }
        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,encoding);
        HttpPost post=new HttpPost(path);
        post.setEntity(entity);
        DefaultHttpClient client=new DefaultHttpClient();
        HttpResponse response=client.execute(post);
        if(response.getStatusLine().getStatusCode()==200){
            result= EntityUtils.toString(response.getEntity());      //获得response数据
        }
        System.out.println(result+"返回信息");
        return result;
    }
    private void parseJson(InputStream instream) throws Exception {
        byte[]data=Util.getByte(instream);
        String json=new String(data);
        System.out.print(json+"json");
        if(json.equals("fail")){

        }else{
            System.out.println(json+"返回信息");
            JSONArray array=new JSONArray(json);

            for(int i=0;i

NewsAdapter

public class NewsAdapter extends BaseAdapter implements AbsListView.OnScrollListener {
    private List mList;
    private LayoutInflater mInflater;
    private ImageLoader imageLoader;
    private int mStart,mEnd;
    public static String[] URLS;//保存所有图片URl地址
    private boolean mFirstIn;
    public NewsAdapter(Context context, List mList, ListView listview) {
        super();
        this.mList = mList;
        mInflater =LayoutInflater.from(context);
        imageLoader=new ImageLoader(listview);
        URLS=new String[mList.size()];
        for(int i=0;ivcon="(ImageView)" viewholder.tvcontent="(TextView)" visibleitemcount="" void="">0){
            imageLoader.loadImage(mStart,mEnd);
            mFirstIn=false;
        }
    }

}

ImageLoader

public class ImageLoader {

    private ImageView mImageView;
    private String mUrl;
    //创建cache
    private LruCache mCaches;
    private ListView mListView;
    private Set mTask;



    public ImageLoader(ListView listview) {
        mListView=listview;
        mTask=new HashSet();
        //获取最大可用内存
        int maxMemory=(int) Runtime.getRuntime().maxMemory();
        int cacheSize=maxMemory/4;
        mCaches = new LruCache(cacheSize){
            @SuppressLint("NewApi") @Override
            protected int sizeOf(String key, Bitmap value) {
                //在每次存入的缓存是调用
                return value.getByteCount();
            }
        };
    }


    //将内容保存到Cache中
    public void  addBitmapToCache(String url,Bitmap bitmap){
        //缓存中没有内容,则保存到缓存中
        if(getBitmapFromCache(url)==null){
            mCaches.put(url,bitmap);
        }

    }

    //从Cache中获取内容
    public Bitmap getBitmapFromCache(String url){

        return mCaches.get(url);
    }
    private Handler mhandler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO 自动生成的方法存根
            super.handleMessage(msg);
            if(mImageView.getTag().equals(mUrl))
                mImageView.setImageBitmap((Bitmap)msg.obj);
        }
    };
    public void showImageByThread(ImageView imageView,final String url){
        mImageView=imageView;
        mUrl=url;
        new Thread(){

            @Override
            public void run() {
                // TODO 自动生成的方法存根
                super.run();
                Bitmap bitmap=getBitmapFromUrl(url);
                Message message=Message.obtain();
                message.obj=bitmap;
                mhandler.sendMessage(message);
            }

        }.start();
    }

    public Bitmap getBitmapFromUrl(String urlString){
        Bitmap bitmap;
        InputStream is = null;
        try {
            URL url=new URL(urlString);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            is=new BufferedInputStream(connection.getInputStream());
            BitmapFactory.Options options=new BitmapFactory.Options();
            options.inSampleSize = 2;
            bitmap=BitmapFactory.decodeStream(is,null,options);
            connection.disconnect();
            return bitmap;
        } catch (MalformedURLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        finally{
            try {
                is.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        return null;

    }


    public void showImageByAsyncTask(ImageView imagview,String url){
        //先从缓存中取出对应的图片
        Bitmap bitmap=getBitmapFromCache(url);
        //如果缓存中没有,则必须从网络中下载
        if(bitmap==null){
            //new NewsAsyncTask(imagview,url).execute(url);
            imagview.setImageResource(R.drawable.ic_launcher);
        }
        else{
            imagview.setImageBitmap(bitmap);
        }
    }


    //取消加载任务
    public void cancelAllTAsks(){
        if(mTask!=null){
            for(NewsAsyncTask task:mTask){
                task.cancel(false);
            }
        }


    }

    //用于加载从start到end的图片
    public void loadImage(int start,int end){

        for(int i=start;i {
        // public ImageView mimageview;
        private String mUrl;

        public NewsAsyncTask(String murl) {
            super();
            //this.mimageview = mimageview;
            this.mUrl = murl;
        }
        @Override
        protected Bitmap doInBackground(String... params) {
            String url=params[0];
            //从网络获取图片
            Bitmap bitmap=getBitmapFromUrl(url);
            if(bitmap!=null){
                //将不在缓存的图片加入缓存
                addBitmapToCache(url, bitmap);
            }
            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
//          if(mimageview.getTag().equals(murl))
//          mimageview.setImageBitmap(result);
            ImageView imageView=(ImageView) mListView.findViewWithTag(mUrl);
            if(imageView!=null && result!=null){
                imageView.setImageBitmap(result);
            }
            mTask.remove(this);

        }
    }

}

SelectPictureHanlder

public class SelectPictureHanlder implements Runnable {


    private Handler handler;
    private String flag;
    private String id;
    public ArrayList piclist = new ArrayList();
    public SelectPictureHanlder(Handler handler,String flag,String id) {
        super();
        this.handler = handler;
        this.flag=flag;
        this.id = id ;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        String result;
        Map params=new HashMap();
        params.put("flag", flag);
        try {
            result=Util.sendPostRequest(Info.path10+id, params, "UTF-8");

            if(result.equals("暂无数据")){
                handler.sendEmptyMessage(0);

            }
            else{
                parseJson(result);
            }
        }
        catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void parseJson(String instream) throws JSONException {
        // TODO Auto-generated method stub
        if(instream.equals("fail"))
        {

            handler.sendEmptyMessage(0);
        }
        else{
            JSONArray array=new JSONArray(instream);
            System.out.println(array.length()+"----->");
            System.out.println("JSonArray.length"+array.length()+"");
            for(int i=0;i

PictureActivity

public class PictureActivity extends Activity {


    private Intent a;
    private ImageView imgView;
    private ImageView imgView2;
    private String dapengid;
    private Button btn_next;
    private Handler pic_hdl,handler;
    private ListView listview;
    private ArrayList piclist;
    private ProgressDialog mDialog;
//    private FragmentManager manager;
//         private FragmentTransaction transaction;
    final  String Path="保密" ;
    private SelectPictureHanlder selectPictureHanlder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.picture);
        imgView=(ImageView) findViewById(R.id.imgv);
        imgView2=(ImageView) findViewById(R.id.imgv2);
        listview=(ListView)findViewById(R.id.piclist);
        a = getIntent();
        dapengid = a.getStringExtra("id");
//        manager = getFragmentManager();
//        transaction = manager.beginTransaction();
//        final PictureFragment pictureFragment = new PictureFragment();


        handler=new Handler()
        {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                switch (msg.what) {
                    case 0:
                        Toast.makeText(PictureActivity.this, "查询请求失败",Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        for(int i=0;i0){
                            NewsAdapter adapter=new NewsAdapter(PictureActivity.this,selectPictureHanlder.piclist,listview);
                            listview.setAdapter(adapter);
                           /* listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                @Override
                                public void onItemClick(AdapterView parent, View view,
                                                        int position, long id) {
                                    // TODO 自动生成的方法存根
                                    ImageView imageview=(ImageView) view.findViewById(R.id.image_p);
                                    imageview.buildDrawingCache();
                                    Bitmap bmap = imageview.getDrawingCache();
                                    onThumbnailClick(bmap);
                                }
                            });*/
                        }
                        break;
                    default:
                        break;
                }
            }

        };
        selectPictureHanlder =new SelectPictureHanlder(handler,"1",dapengid);
        new Thread(selectPictureHanlder).start();
        System.out.println("查询线程已启动");
    }


    public void onThumbnailClick(Bitmap bmap) {
//          final AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
//          ImageView imgView = getImageView(bmap);
//          dialog.setView(imgView);
//          dialog.show();

        // 全屏显示的方法
        final Dialog dialog = new Dialog(PictureActivity.this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
        ImageView imgView = getImageView(bmap);
        dialog.setContentView(imgView);
        dialog.show();

        // 点击图片消失
        imgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
    }



    private ImageView getImageView(Bitmap bmap) {
        ImageView imgView = new ImageView(PictureActivity.this);
        imgView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        imgView.setImageBitmap(bmap);
        return imgView;
    }




    private class  ViewHolder{
        private ImageView mimageview;
        private TextView textView;
    }


    public Bitmap getUrlImage(String url) {

        Bitmap img = null;
        try {
            URL picurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)picurl.openConnection();
            conn.setConnectTimeout(6000);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            InputStream is = conn.getInputStream();
            try{
                is = conn.getInputStream();
                BitmapFactory.Options options=new BitmapFactory.Options();
                options.inSampleSize = 4;
                img = BitmapFactory.decodeStream(is,null,options);
            }
            catch(Exception e)
            {
                Toast.makeText(PictureActivity.this, "加载图片过大,请稍后重试",Toast.LENGTH_LONG).show();
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return img;
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode==KeyEvent.KEYCODE_HOME)
            finish();
        if(keyCode==KeyEvent.KEYCODE_BACK){
//            Intent intent=new Intent(PictureActivity.this,MainActivity.class );
//
//            startActivity(intent);
            finish();
        }
        return false;
    }
}
点击复制链接 与好友分享!回本站首页
上一篇:Android Studio3.0中dependencies依赖由compile变为implementation的区别
下一篇:Android Studio连接网易MuMu模拟器
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站