服务器之家

服务器之家 > 正文

Android图片上传实现预览效果

时间:2021-05-20 16:24     来源/作者:Hankkin

首先具体分析一下,实现的功能,其中需求分析是必不可少的,需求、逻辑清除之后,再上手写代码,思路会很清晰。

1.多图上传首先得选择图片(这里项目需求是既可以拍照上传也可以从相册中选择)

2.拍照上传很简单了网上也有很多例子,调用照相机,返回uri,获取图片

3.从相册中选择图片

  •  3.1 获取手机中的所有图片
  •  3.2 将图片存到自定义图片数组中显示
  •  3.3 自定义viewpager浏览图片

主要的逻辑大体是这样,下面具体看一下实现:

一、首先看一下界面:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<com.view.noscrollgridview
          android:id="@+id/noscrollgridview"
          android:layout_marginleft="@dimen/smaller_space"
          android:layout_marginright="@dimen/smaller_space"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:horizontalspacing="3dp"
          android:listselector="@color/transparent"
          android:numcolumns="3"
          android:scrollbars="none"
          android:layout_gravity="center"
          android:layout_margintop="@dimen/smaller_space"
          android:verticalspacing="5dp" />

是一个 noscrollgridview,项目需要,所以用了不滚动的gridview,大家用gridview也是一样的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
noscrollgridview = (gridview) findviewbyid(r.id.noscrollgridview);
    noscrollgridview.setselector(new colordrawable(color.transparent));
    /*新建传值给adapter*/
    if (file == null) {
      picadapter = new pictureadapter(this, 0, null);
    } else {
      //添加失败的图片到数组中
      for (int i=0;i<file.getmulfailfilepaths().length;i++){
        imageitem imageitem = new imageitem();
        imageitem.setimagepath(file.getmulfailfilepaths()[i].trim());
        bimp.tempselectbitmap.add(imageitem);
      }
      /*上传失败传值给adapter*/
      picadapter = new pictureadapter(this, 2, file);
    }

这个是初始化图片数组,适配器(新建、上传失败、上传成功的图片我用的都是一个adapter)

imageitem是图片的模型,下面有它的属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//从图库选择的图片model
public class imageitem extends file implements serializable {
  @id
  public string imageid; //图片id
  public string thumbnailpath; 
  public string imagepath; //图片路径
  private bitmap bitmap; 
  public boolean isselected = false;
   
  public string getimageid() {
    return imageid;
  }
  public void setimageid(string imageid) {
    this.imageid = imageid;
  }
  public string getthumbnailpath() {
    return thumbnailpath;
  }
  public void setthumbnailpath(string thumbnailpath) {
    this.thumbnailpath = thumbnailpath;
  }
  public string getimagepath() {
    return imagepath;
  }
  public void setimagepath(string imagepath) {
    this.imagepath = imagepath;
  }
  public boolean isselected() {
    return isselected;
  }
  public void setselected(boolean isselected) {
    this.isselected = isselected;
  }
[java] view plain copy print?
/*根据图片路径获取图片的bitmap*/
public bitmap getbitmap() {     
  if(bitmap == null){
    try {
      bitmap = bimp.revitionimagesize(imagepath);
    } catch (ioexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }
  }
  return bitmap;
}
public void setbitmap(bitmap bitmap) {
  this.bitmap = bitmap;
}

 接下来是适配器:

由于涉及到添加图片,adapter中添加一个flag用来显示新建的图片,将选择的图片添加到公有的图片数组中,初始化的时候加载图片数组显示。(大家在看的时候可以忽略掉我的flag)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@suppresslint("handlerleak")
public class pictureadapter extends baseadapter {
  private layoutinflater inflater;
  private int selectedposition = -1;
  private boolean shape;
  private int flag = 0;//0 默认新建 1上传成功 2上传失败
  private appitem_file file;
  public boolean isshape() {
    return shape;
  }
  private activity context;
 
  public void setshape(boolean shape) {
    this.shape = shape;
  }
 
  public pictureadapter(activity context,int flag,appitem_file file) {
    this.context = context;
    inflater = layoutinflater.from(context);
    this.flag = flag;
    this.file = file;
  }
 
//  public void update() {
//    loading();
//  }
 
  public int getcount() {
    if (flag==0){  //新建图片
      if (bimp.tempselectbitmap.size() == 6) {
        return 6;
      }
      return (bimp.tempselectbitmap.size() + 1);
    }
    else if (flag==1){ //上传成功
      return file.getfilelist().size();
    }
    else { //上传失败
      return file.getmulfailfilepaths().length;
    }
 
  }
 
 
 
  public object getitem(int arg0) {
    if (flag==1){
      return file.getfilelist().get(arg0);
    }else {
      return file.getmulfailfilepaths()[arg0];
    }
  }
 
  public long getitemid(int arg0) {
    return arg0;
  }
 
  public void setselectedposition(int position) {
    selectedposition = position;
  }
 
  public int getselectedposition() {
    return selectedposition;
  }
 
  public view getview(int position, view convertview, viewgroup parent) {
    viewholder holder = null;
    if (convertview == null) {
      //根据图片的数量加载不同布局
      if (getcount()==1&&flag!=0){
        convertview = inflater.inflate(r.layout.item_published_singal_item,
            parent, false);
      }
      else {
        convertview = inflater.inflate(r.layout.item_published_grida,
            parent, false);
      }
 
      holder = new viewholder();
      holder.image = (imageview) convertview
          .findviewbyid(r.id.item_grida_image);
      convertview.settag(holder);
    } else {
      holder = (viewholder) convertview.gettag();
    }
 
    /**
     * 根据初始化adapter传过来的flag值,去不同的地方找图片
     * flag=0,去bimp的图片数组中找
     * flag=1,证明上传成功的,去下载好的getfilelist中找
     * flag=2,为上传失败的,图片保存在failfile中的list<imageitem>中
     * 优化图片显示
     */
    if (flag==0){  //新建图片
      if (position == bimp.tempselectbitmap.size()) {
        holder.image.setimagebitmap(bitmapfactory.decoderesource(
            convertview.getresources(), r.drawable.icon_add_pic_unfocused));
        if (position == 6) {
          if (flag==0){
            holder.image.setvisibility(view.gone);
          }
        }
      } else {
        holder.image.setimagebitmap(bimp.tempselectbitmap.get(position).getbitmap());
      }
    }
    else if (flag==1){ //上传成功
//      list<integer> ids = new arraylist<integer>();
//      for (int i=0;i<file.getfilelist().size();i++){
//        ids.add(file.getfilelist().get(i).gets_id());
//      }
      int id=file.getfilelist().get(position).gets_id();
      try {
//        file file= needapplication.db.findbyid(file.class,id);
        string filebigimguri =needapplication.db.findbyid(file.class,id).getfileuribig();
        if (filebigimguri!=null&&!"null".equals(filebigimguri))
        imageloader.getinstance().displayimage((filebigimguri).trim(),holder.image);
      } catch (dbexception e) {
        e.printstacktrace();
      }
    }
    else { //上传失败
        string url = "file://"+file.getmulfailfilepaths()[position].trim();
        imageloader.getinstance().displayimage(url, holder.image);
    }
 
 
    return convertview;
  }
 
  public class viewholder {
    public imageview image;
  }
 
}

 下面是自定义相册界面,用来选择图片的

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#e1e0de"
  >
 
  <relativelayout
    android:id="@+id/headview"
    android:layout_width="fill_parent"
    android:layout_height="45dp"
    android:background="@drawable/plugin_camera_title_bar"
    android:gravity="center_vertical"
    android:layout_marginbottom="3dp"
    >
    <button
      android:layout_width="60dp"
      android:layout_height="wrap_content"
      android:textsize="14sp"
      android:textcolor="#fff"
      android:id="@+id/back"
      android:text="相册"
      android:background="@drawable/plugin_camera_title_btn_back"
      android:layout_margintop="5dp"
      android:layout_marginbottom="5dp"
      android:layout_centervertical="true"
      />
    <button
      android:layout_width="67dp"
      android:layout_height="wrap_content"
      android:textsize="14sp"
      android:textcolor="#fff"
      android:id="@+id/cancel"
      android:text="取消"
      android:background="@drawable/plugin_camera_title_btn_cancel"
      android:layout_centervertical="true"
      android:layout_marginright="5dp"
      android:layout_alignparentright="true"
      />
  </relativelayout>
 
  <relativelayout
    android:id="@+id/bottom_layout"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignparentbottom="true"
    android:background="@drawable/plugin_camera_bottom_bar"
    android:layout_margintop="3dp"
    >
    <button
      android:id="@+id/preview"
      android:layout_width="90dp"
      android:layout_height="wrap_content"
      android:layout_alignparentleft="true"
      android:layout_centervertical="true"
      android:layout_marginleft="10dp"
      android:text="预览"
      android:background="@drawable/plugin_camera_title_btn_preview"
      />
    <button
      android:id="@+id/ok_button"
      android:layout_width="90dp"
      android:layout_height="wrap_content"
      android:layout_alignparentright="true"
      android:layout_centervertical="true"
      android:layout_marginright="10dp"
      android:background="@drawable/plugin_camera_ok_btn_state"
      />
  </relativelayout>
 
  <gridview
    android:id="@+id/mygrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@id/bottom_layout"
    android:layout_below="@id/headview"
    android:layout_centerinparent="true"
    android:layout_margintop="2dp"
    android:horizontalspacing="10dp"
    android:numcolumns="4"
    android:verticalspacing="10dp"
    android:background="#e1e0de" />
  <textview
    android:id="@+id/mytext"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="相册没有图片"
    android:textcolor="@color/black"
    />
 
</relativelayout>

 同样也是用了gridview,获取手机中的图片,添加到数组中,显示

这里用到了一个albumhelper(相册帮助类),网上找的代码,感觉挺好的

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public list<imagebucket> getimagesbucketlist(boolean refresh) {
    if (refresh || (!refresh && !hasbuildimagesbucketlist)) {
      buildimagesbucketlist();
    }
    list<imagebucket> tmplist = new arraylist<imagebucket>();
    iterator<entry<string, imagebucket>> itr = bucketlist.entryset()
        .iterator();
    while (itr.hasnext()) {
      entry<string, imagebucket> entry = (entry<string, imagebucket>) itr
          .next();
      tmplist.add(entry.getvalue());
    }
    return tmplist;
  }

获取到数据源之后,该显示了,也就是利用的获取图片帮助类里面的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 初始化,给一些对象赋值
  private void init() {
    helper = albumhelper.gethelper();
    helper.init(getapplicationcontext());
     
    contentlist = helper.getimagesbucketlist(false);
    datalist = new arraylist<imageitem>();
    for(int i = 0; i<contentlist.size(); i++){
      datalist.addall( contentlist.get(i).imagelist );
    }
     
    back = (button) findviewbyid(r.id.back);
    cancel = (button) findviewbyid(r.id.cancel);
    cancel.setonclicklistener(new cancellistener());
    back.setonclicklistener(new backlistener());
    preview = (button) findviewbyid(r.id.preview);
    preview.setonclicklistener(new previewlistener());
    intent = getintent();
    bundle bundle = intent.getextras();
    gridview = (gridview) findviewbyid(r.id.mygrid);
    gridimageadapter = new albumgridviewadapter(mcontext,datalist,bimp.tempselectbitmap);
    gridview.setadapter(gridimageadapter);
    tv = (textview) findviewbyid(r.id.mytext);
    gridview.setemptyview(tv);
    okbutton = (button) findviewbyid(r.id.ok_button);
    okbutton.settext("完成"+"(" + bimp.tempselectbitmap.size()
        + "/"+ needapplication.picnums+")");
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
gridimageadapter
        .setonitemclicklistener(new albumgridviewadapter.onitemclicklistener() {
 
          @override
          public void onitemclick(final togglebutton togglebutton,
              int position, boolean ischecked,button choosebt) {
            if (bimp.tempselectbitmap.size() >= needapplication.picnums) {
              togglebutton.setchecked(false);
              choosebt.setvisibility(view.gone);
              if (!removeonedata(datalist.get(position))) {
                toast.maketext(albumactivity.this, "超出可选图片张数", toast.length_short).show();
              }
              return;
            }
            if (ischecked) {
              choosebt.setvisibility(view.visible);
              bimp.tempselectbitmap.add(datalist.get(position));
              okbutton.settext("完成"+"(" + bimp.tempselectbitmap.size()
                  + "/"+ needapplication.picnums+")");
            } else {
              bimp.tempselectbitmap.remove(datalist.get(position));
              choosebt.setvisibility(view.gone);
              okbutton.settext("完成"+"(" + bimp.tempselectbitmap.size() + "/"+ needapplication.picnums+")");
            }
            isshowokbt();
          }
        });

点击图片选择加到公有图片数组中显示已选择。

最后是预览图片,利用自定义viewpager,实现图片滑动,下面贴两张截图吧:

Android图片上传实现预览效果

以上就是本文的全部内容,希望对大家的学习有所帮助。

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部