欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android 实现APP中改变头像图片的实例代码

程序员文章站 2024-01-24 13:06:04
具体代码如下所示: package com.example.studyapplication.fragment; import android.app.acti...

具体代码如下所示:

package com.example.studyapplication.fragment;
import android.app.activity;
import android.app.alertdialog;
import android.content.context;
import android.content.intent;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.graphics.canvas;
import android.graphics.color;
import android.graphics.paint;
import android.graphics.porterduff;
import android.graphics.porterduffxfermode;
import android.graphics.drawable.bitmapdrawable;
import android.graphics.drawable.drawable;
import android.net.uri;
import android.os.bundle;
import android.os.environment;
import android.provider.mediastore;
import android.support.annotation.nullable;
import android.support.v4.app.fragment;
import android.text.spannable;
import android.text.spannablestring;
import android.text.spanned;
import android.text.method.linkmovementmethod;
import android.text.style.foregroundcolorspan;
import android.text.style.urlspan;
import android.util.log;
import android.view.layoutinflater;
import android.view.view;
import android.view.viewgroup;
import android.widget.button;
import android.widget.imagebutton;
import android.widget.imageview;
import android.widget.linearlayout;
import android.widget.textview;
import com.example.studyapplication.mainactivity;
import com.example.studyapplication.r;
import com.example.studyapplication.wode_activity;
import com.example.studyapplication.zhubanfangactivity;
import com.example.studyapplication.zhuceactivity;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.lang.ref.weakreference;
import static android.app.activity.result_ok;
public class wodefragment extends fragment implements view.onclicklistener {
  private view mview;
  private context mavtivity;
  button youhuiquan;
  button shoucang;
  button guanzhu;
  imageview shezhi;
  imageview xiaoxi;
  textview qiehuanweizhuban;
  static  textview denglu;
  linearlayout daifukuan;
  linearlayout daicanyu;
  linearlayout tuikuan;
  linearlayout yiwancheng;
  linearlayout qingxiandenglu;
  linearlayout log;
  linearlayout quanbudingdan;
  private button ll01,ll02,ll03;
  private context mcontext;
  private imagebutton touxiang;
  private bitmap head;// 头像bitmap
  private static string path = "/sdcard/myhead/";// sd路径
  activity mactivity;
  uri uritempfile;
  public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) {
    mview = inflater.inflate(r.layout.wode_layout, null);
    mactivity=this.getactivity();
    //设置布局文件5888
    return mview;
  }
  @override
  public void oncreate(@nullable bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    this.mcontext = getactivity();
  }
    /*
    点击头像进行更换头像
     */
    touxiang.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        switch (v.getid()) {
          case r.id.touxiang:// 更换头像
            showtypedialog();
            break;
        }
      }
    });
  }
  private void initview() {
    ll01=(button)getactivity().findviewbyid(r.id.youhuiquan);
    ll02=(button) getactivity().findviewbyid(r.id.shoucang);
    ll03=(button)getactivity().findviewbyid(r.id.guanzhu);
    touxiang = (imagebutton)getactivity().findviewbyid(r.id.touxiang);
    bitmap bt = bitmapfactory.decodefile(path + "log.png");// 从sd卡中找头像,转换成bitmap
    if (bt != null) {
      @suppresswarnings("deprecation")
      drawable drawable = new bitmapdrawable(bt);// 转换成drawable
      touxiang.setimagedrawable(drawable);
    } else {
      /**
       * 如果sd里面没有则需要从服务器取头像,取回来的头像再保存在sd中
       *
       */
    }
  }
  private void showtypedialog() {
    //显示对话框
    alertdialog.builder builder = new alertdialog.builder(getactivity());
    final alertdialog dialog = builder.create();
    view view = view.inflate(getactivity(), r.layout.dialog_select_photo, null);
    textview tv_select_gallery = (textview) view.findviewbyid(r.id.tv_select_gallery);
    textview tv_select_camera = (textview) view.findviewbyid(r.id.tv_select_camera);
    tv_select_gallery.setonclicklistener(new view.onclicklistener() {// 在相册中选取
      @override
      public void onclick(view v) {
        intent intent1 = new intent(intent.action_pick, null);
        //打开文件
        intent1.setdataandtype(mediastore.images.media.external_content_uri, "image/log.png");
        startactivityforresult(intent1, 1);
         dialog.dismiss();
      }
    });
    tv_select_camera.setonclicklistener(new view.onclicklistener() {// 调用照相机
      @override
      public void onclick(view v) {
        intent intent2 = new intent(mediastore.action_image_capture);
        intent2.putextra(mediastore.extra_output,
            uri.fromfile(new file(environment.getexternalstoragedirectory(), "log.png")));
        startactivityforresult(intent2, 2);// 采用forresult打开
        dialog.dismiss();
      }
    });
    dialog.setview(view);
    dialog.show();
  }
  @override
  public void onactivityresult(int requestcode, int resultcode, intent data) {
    switch (requestcode) {
      case 1:
        if (resultcode == result_ok) {// 如果返回码是可以用的
          cropphoto(data.getdata());// 裁剪图片
        }
        break;
      case 2:
        if (resultcode == result_ok) {
          file temp = new file(environment.getexternalstoragedirectory() + "/head.jpg");
          cropphoto(uri.fromfile(temp));// 裁剪图片
        }
        break;
      case 3:
        if (data != null) {
          uri extras = data.getdata();
          //head = extras.getparcelable("data");
          try {
            head=bitmapfactory.decodestream(mactivity.getcontentresolver().openinputstream(uritempfile));
          } catch (filenotfoundexception e) {
            e.printstacktrace();
          }
          if (head != null) {
            /**
             * 上传服务器代码
             */
            // 让刚才选择裁剪得到的图片显示在界面上
            setpictoview(head);// 保存在sd卡中
            touxiang.setimagebitmap(head);// 用imagebutton显示出来
          }
        }
        break;
      default:
        break;
    }
    super.onactivityresult(requestcode, resultcode, data);
  }
  /**
   * 调用系统的裁剪功能
   *
   * @param uri
   */
  public void cropphoto(uri uri) {
    if(uri== null){
      log.i("tag","the uri is not exist.");
    }
    intent intent = new intent("com.android.camera.action.crop");
    intent.setdataandtype(uri, "image/*.png");
    //设置裁剪
    intent.putextra("crop", "true");
    // aspectx aspecty 是宽高的比例
    intent.putextra("aspectx", 1);
    intent.putextra("aspecty", 1);
    // outputx outputy 是裁剪图片宽高
    intent.putextra("outputx", 250);
    intent.putextra("outputy", 250);
    intent.putextra("return-data", true);
    uritempfile = uri.parse("file:///sdcard/temp.jpg");//重要,android4.0以上,本地地址前都加file://+/
    // uritempfile=uri;
    intent.putextra(mediastore.extra_output, uritempfile);
    intent.putextra("outputformat", bitmap.compressformat.jpeg.tostring());
    startactivityforresult(intent, 3);
  }
  private void setpictoview(bitmap mbitmap) {
    string sdstatus = environment.getexternalstoragestate();
    if (!sdstatus.equals(environment.media_mounted)) { // 检测sd是否可用
      return;
    }
    fileoutputstream b = null;
    file file = new file(path);
    file.mkdirs();// 创建文件夹
    string filename = path + "log.png";// 图片名字
    try {
      b = new fileoutputstream(filename);
      mbitmap.compress(bitmap.compressformat.jpeg, 100, b);// 把数据写入文件
    } catch (filenotfoundexception e) {
      e.printstacktrace();
    } finally {
      try {
        // 关闭流
        b.flush();
        b.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
  }
//生成圆角图片-------未使用
  private bitmap getroundedcornerbitmap(bitmap bitmap){
    bitmap roundbitmap = bitmap.createbitmap(bitmap.getwidth(),bitmap.getheight(), bitmap.config.argb_8888);
    canvas canvas =new canvas(roundbitmap);
    int color=0xff424242;
    paint paint=new paint();
    //设置圆形半径
    int radius;
    if( bitmap.getwidth()>bitmap.getheight()){
      radius=bitmap.getheight()/2;
    }else {
      radius=bitmap.getwidth()/2;
    }
    //绘制圆形
    paint.setantialias(true);
    canvas.drawargb(0,0,0,0);
    paint.setcolor(color);
    canvas.drawcircle(bitmap.getwidth()/2,bitmap.getheight()/2,radius,paint);
    paint.setxfermode(new porterduffxfermode(porterduff.mode.src_in));
    canvas.drawbitmap(bitmap,0,0,paint);
    return roundbitmap;
  }
}

注意:手机权限一定要设置,这个非常重要

android 实现APP中改变头像图片的实例代码

androidmanifest.xml:

 <uses-permission android:name="android.permission.mount_unmount_filesystems"  tols:ignore="protectedpermissions" />

总结

以上所述是小编给大家介绍的android 实现app中改变头像图片的实例代码,希望对大家有所帮助