码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-12-22 17:49:01      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

 

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 {

        }
    }

}

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

标签:

原文地址:http://www.cnblogs.com/520-1314/p/5067376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!