用户头像重相册或相机里获取

user_info_head_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/user_info_head_background" >

    <RelativeLayout
        android:id="@+id/user_info_head_relativelayout1"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_alignParentTop="true"
        android:background="@color/title_color" >

        <Button
            android:id="@+id/user_info_head_back"
            android:layout_width="@dimen/icon_back"
            android:layout_height="@dimen/icon_back"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:background="@drawable/back_icon" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="@string/user_head_image"
            android:textColor="@color/white"
            android:textSize="22sp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/user_info_head_relativelayout2"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_below="@+id/user_info_head_relativelayout1" >

        <com.etoury.etoury.ui.view.CircleImg
            android:id="@+id/user_info_head_img"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_centerInParent="true"
            android:src="@drawable/ic_user" >
        </com.etoury.etoury.ui.view.CircleImg>

        <!--
             <ImageView
            android:id="@+id/user_info_head_img"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_centerInParent="true"
            android:src="@drawable/ic_user" />
        -->
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_below="@+id/user_info_head_relativelayout2"
        android:background="@color/white" >

        <ImageView
            android:id="@+id/select_from_photo_album_img"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="@drawable/select_from_photo_album"
            android:contentDescription="@null" />

        <ImageView
            android:id="@+id/line_img1"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_alignBottom="@+id/select_from_photo_album_img"
            android:layout_toRightOf="@+id/select_from_photo_album_img"
            android:background="@drawable/user_info_line"
            android:contentDescription="@null" />

        <LinearLayout
            android:id="@+id/user_info_head_linearlayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/line_img1"
            android:layout_marginBottom="5dp"
            android:layout_marginRight="10dp"
            android:layout_toRightOf="@+id/select_from_photo_album_img"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/select_from_photo_album_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:text="@string/select_from_photo_album" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="" />

            <ImageView
                android:id="@+id/select_from_photo_album_img1"
                android:layout_width="10dp"
                android:layout_height="20dp"
                android:layout_gravity="center_vertical"
                android:layout_margin="5dp"
                android:background="@drawable/right_arrows_icon"
                android:contentDescription="@null" />
        </LinearLayout>

        <ImageView
            android:id="@+id/take_photos_img"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_below="@+id/select_from_photo_album_img"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="@drawable/take_photos"
            android:contentDescription="@null" />

        <ImageView
            android:id="@+id/line_img2"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_alignBottom="@+id/take_photos_img"
            android:layout_toRightOf="@+id/take_photos_img"
            android:background="@drawable/user_info_line"
            android:contentDescription="@null" />

        <LinearLayout
            android:id="@+id/user_info_head_linearlayout2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/line_img2"
            android:layout_marginBottom="5dp"
            android:layout_marginRight="10dp"
            android:layout_toRightOf="@+id/take_photos_img"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/take_photos_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:text="@string/take_photos" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="" />

            <ImageView
                android:id="@+id/take_photos_img1"
                android:layout_width="10dp"
                android:layout_height="20dp"
                android:layout_gravity="center_vertical"
                android:layout_margin="5dp"
                android:background="@drawable/right_arrows_icon"
                android:contentDescription="@null" />
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

UserInfoHeadActivity.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.etoury.etoury.bean.FileImage;
import com.etoury.etoury.http.Url;
import com.etoury.etoury.util.JsonUtil;
import com.etoury.etoury.util.SharedPreferencesUtil;
import com.etoury.project.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class UserInfoHeadActivity extends Activity implements OnClickListener {

    private static final int PHOTO_REQUEST_GALLERY = 1;// 相册
    private static final int PHOTO_REQUEST_CAMERA = 2;// 拍照
    public static final int PHOTO_REQUEST_CUT = 3;// 裁剪
    private Uri cameraUri;

    private Button user_info_head_back;
    private LinearLayout linearLayout1;
    private LinearLayout linearLayout2;
    private ImageView user_info_head_img;

    private Bitmap bitmap,backBitmap;

    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    /* Bitmap头像名称 */
    private static final String BITMAP_PHOTO_FILE_NAME = "bitmap_temp_photo.jpg";
    /* 储存图片文件名字 */
    private File tempFile, bitmapFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.user_info_head_activity);
        initView();

    }

    private void initView() {
        user_info_head_back = (Button) findViewById(R.id.user_info_head_back);
        linearLayout1 = (LinearLayout) findViewById(R.id.user_info_head_linearlayout1);
        linearLayout2 = (LinearLayout) findViewById(R.id.user_info_head_linearlayout2);
        user_info_head_img = (ImageView) findViewById(R.id.user_info_head_img);

        user_info_head_back.setOnClickListener(this);
        linearLayout1.setOnClickListener(this);
        linearLayout2.setOnClickListener(this);
        // user_info_head_img.setOnClickListener(this);

        Intent intent = getIntent();
        Bitmap bitmap = intent.getParcelableExtra("Bitmap");
        if (bitmap != null) {
            user_info_head_img.setImageBitmap(bitmap);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.user_info_head_back:
            // 返回Bitmap给上一个活动
            System.out.println("返回Bitmap给上一个活动**********" + backBitmap);
            Intent intent = new Intent();

            if (backBitmap!=null) {
                intent.putExtra("backBitmap", backBitmap);
                setResult(RESULT_OK, intent);
            }

            System.out.println("返回Bitmap给上一个活动" + backBitmap);

            finish();

            break;
        case R.id.user_info_head_linearlayout1:

            gallery();

            break;
        case R.id.user_info_head_linearlayout2:

            camera();

            break;
        default:
            break;
        }

    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 从相册获取
     */
    public void gallery() {

        // 定向到图片库
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    /*
     * 从相机获取
     */
    private void camera() {

        if (hasSdcard()) {
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    PHOTO_FILE_NAME);
            try {
                if (tempFile.exists()) {
                    tempFile.delete();
                }
                tempFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        cameraUri = Uri.fromFile(tempFile);

        // 意图 相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);

        startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }

    /**
     * 裁剪
     */
    private void crop(Uri uri) {

        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);// 去黑边
        // 裁剪框的比例,1:1
        intent.putExtra("aspectX", 1);// 输出是X方向的比例
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        // 图片格式
        /* intent.putExtra("outputFormat", "JPEG"); */
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:返回uri,false:不返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void saveCroppedImage(Bitmap bmp) {

        System.out.println("裁剪返回的bitmap" + bitmap);
        bitmapFile = new File(Environment.getExternalStorageDirectory(),
                BITMAP_PHOTO_FILE_NAME);
        System.out.println("bmpfile" + bitmapFile);
        if (bitmapFile.exists()) {
            bitmapFile.delete();
        }
        try {
            bitmapFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Bitmap变成一个流
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(bitmapFile);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos);
        this.bitmap = bmp;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
            case PHOTO_REQUEST_GALLERY:
                System.out.println("data.getData()返回的uri" + data.getData());
                crop(data.getData());

                break;
            case PHOTO_REQUEST_CAMERA:
                System.out.println("cameraUri返回的uri" + cameraUri);

                crop(cameraUri);

                break;
            case PHOTO_REQUEST_CUT:
                try {
                    Bitmap cropbitmap = data.getParcelableExtra("data");
                    saveCroppedImage(cropbitmap);
                    // 上传网络
                    upload();
                    user_info_head_img.setImageBitmap(bitmap);
                    backBitmap = bitmap;

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            default:
                return;
            }
        }
    }

    /*
     * 上传图片
     */
    public void upload() {
        System.out.println("上传图片");
        try {

            AsyncHttpClient client = new AsyncHttpClient();
            // 指定url路径
            String url = Url.FORMUP;
            // 封装文件上传的参数
            RequestParams params = new RequestParams();
            // 根据路径创建文件

            params.put("myfile", bitmapFile);

            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers,
                        byte[] responseBody) {
                    try {
                        if (statusCode == 200) {

                            Toast.makeText(UserInfoHeadActivity.this,
                                    "头像上传成功!", 0).show();

                            String response = new String(responseBody);

                            paresJsonWithGSON(response);

                        } else {
                            Toast.makeText(UserInfoHeadActivity.this,
                                    "网络访问异常,错误码:" + statusCode, 0).show();

                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                        byte[] responseBody, Throwable error) {
                    Toast.makeText(UserInfoHeadActivity.this,
                            "网络访问异常,错误码:" + statusCode, 0).show();

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void paresJsonWithGSON(String response) {

        FileImage fileImage = JsonUtil.parseJsonToBean(response,
                FileImage.class);

        if (fileImage.result.equals("TRUE")) {

            System.out.println("上传头像成功,返回头像的地址:" + fileImage.url);

            System.out.println("更新头像uri");

            SharedPreferencesUtil.remove(getApplicationContext(),
                    "userPutHeadimgUri");

            SharedPreferencesUtil.put(getApplicationContext(),
                    "userPutHeadimgUri", fileImage.url);

        } else {

        }
    }

}
时间: 2024-10-07 14:09:01

用户头像重相册或相机里获取的相关文章

Android中通过访问本地相册或者相机设置用户头像

目前几乎所有的APP在用户注册时都会有设置头像的需求,大致分为三种情况: (1)通过获取本地相册的图片,经过裁剪后作为头像. (2)通过启动手机相机,现拍图片然后裁剪作为头像. (3)在APP中添加一些自带的头像资源,供用户选择(不够人性化,目前很少使用). 这次我们简单介绍下通过获取本地相册以及相机拍摄的方法设置头像,实现思路如下: (1)通过startActivityForResult方法,分别传递调用系统相册的Intent和调用相机拍照的Intent来做选择 (2)调用Android系统中

Android--利用相机或相册截取用户头像(解决了miui无法截取,以及部分机型拍照无返回Uri)

声明 本文的Demo可用于从本地获取用户头像时使用,解决了有些手机系统相机拍照后获取不到拍摄照片的问题,以及解决小米miui系统调用系统裁剪图片功能camera.action.CROP后崩溃或重新打开app的问题. 修改了部分机型拍照后返回的是缩略图的临时文件的问题. 如何获得一张原图 先看代码: UtilClass.requestPermission(ChangeMyDataActivityCopy.this, android.Manifest.permission.CAMERA); choo

从相册获取图片及调用相机拍照获取图片,最后上传图片到服务器

调用相机拍照获取图片: 跳转到到拍照界面: Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //下面这句指定调用相机拍照后的照片存储的路径 mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png"; takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new F

python获取微信公共平台消息列表和用户头像

转载需注明原文地址:http://blog.csdn.net/btyh17mxy/article/details/25207889 刚写的模拟登陆的方式从获取微信公众平台消息列表和用户头像的库,之后还会继续增加相关功能,github地址https://github.com/btyh17mxy/wxwall #!/usr/bin/env python # coding: UTF-8 import json import hashlib import re import random import

Android图片系列(1)-------调用系统相册与相机获取图片

Android开发过程中,我们经常需要获取图片,你可以通过获取手机相册的图片,也可以调用相机拍照获取图片.这里主要讲这两个获取图片的方式,并记录其中遇到的小问题. 调用相册获取图片 这个功能非常简单,这里不多说了,这里贴出关键代码 Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT); openAlbumIntent.setType("image/*"); startActivityForResult(openAl

iOS 开发调用相机以及获取相册照片功能

//添加代理方法 @interface MineViewController () <UITableViewDelegate, UITableViewDataSource, PayCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate> //定义消息框 UIActionSheet * act =[[UIActionSheet alloc]initWi

第一个小程序,获取用户名和用户头像

<!--pages/index/index.wxml--> <!-- 内容封装在view中 --> <view class="content"> <image src='{{src}}'> </image> <text> 欢迎光临 </text> <text class="name"> {{name}} </text> <button open-type

android 用户头像,图片裁剪,上传并附带用户数据base64code 方式

图片上传的文件流我上一篇博客写了,这一篇我们说一下base64,base64上传方式就是将图片转换成base64码,然后把base64码以字符串的方式上传,然后服务器接收到以后再解码就可以了,相对于文件流来说比较简单: 用户头像上传我们首先要获得图片的url然后再裁剪图片,然后把裁剪后的图片转换成base64然后在上传: 下边是安卓端代码: 首先我们要获得裁剪后的图片:一,选择图片: 代码如下,通过对话框选择获得图片的方式: activity: /* * 提示对话框 */ private voi

调用系统相册或相机工具类

需求:点击修改头像,弹出对话框提示选择相册还是相机,从而调用系统相册或相机 import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import