关闭

android头像设置

标签: 头像设置
767人阅读 评论(0) 收藏 举报
分类:

运行效果图:点击拍照或者图片库获取头像
这里写图片描述
但是在anroid4.4版本前后的写法有点不同,可能出现问题。

1、关于拍照调用Intent问题

在4.4版本前可以写成这样:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
activity.startActivityForResult(intent, START_ALBUM_CODE);

或者:

Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
activity.startActivityForResult(intent, START_ALBUM_CODE);

但在4.4版本后就要写成这样了。

Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
activity.startActivityForResult(intent, START_ALBUM_CODE);

2、拍照后保存到sd卡路径问题:

1、保存在sd卡中:sdcard/的路径下
Environment.getExternalStorageDirectory().getAbsolutePath();

2、保存到sd卡下面应用包中:getExternalFilesDir(“/photo”) + “”;这种保存方式可以使卸载应用时,同时也把文件删除,减少sd卡中缓存的垃圾文件。

getExternalFilesDir():一般保存长久文件

getExternalCacheDir():一般保存临时文件

它们的全路径:/storage/emulated/0/Android/data/包名/files/photo

3、头像设置的工作:

  1. 从图片库,或者拍照得到图片;
  2. 图片剪切
  3. 压缩保存图片到本地,并上传服务器
  4. 显示图片时,首先从本地得到。

4、关于图片压缩问题:

bitmap.compress(CompressFormat.JPEG, 70, fos);

0-100.
0 meaning compress for small size,
100 meaning compress for max quality.

quality为图像压缩比的值,0-100.0 意味着小尺寸压缩,100意味着高质量压缩
测试在一张比较小的图片下测试结果:

在保存图片为jpg的情况下:
值 图片大小
0: ——1.34k 图片几乎没办法看,很模糊;
75:——6.67k
100:——24.8k
在保存图片为png的情况下
0: ——–39.38k
75: ——–39.38k
100:—— 39.38k
代码如下:

package com.example.photodemo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final int PICK_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int ZOOM_REQUEST_CODE = 2;

    private static final String IMAGE_FILE_NAME = "photo.jpg";
    private ImageView iv_icon;

    private String[] items = new String[] { "拍照", "图片库" };
    public static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        // 首先判断本地中有没有保存图片:如果没有图片,显示默认图片;
        File file = getExternalFilesDir("/photo");
        String url = file + "/icon.png";
        Bitmap b = BitmapFactory.decodeFile(url);
        if (b != null) {
            iv_icon.setImageBitmap(b);
        }
        iv_icon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showDialog();
            }
        });
    }

    private void showDialog() {
        // TODO Auto-generated method stub
        new AlertDialog.Builder(this).setTitle("选择头像")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        switch (which) {
                        case 0:
                            if (BitmapUtils.isSdcardExisting()) {
                                Intent intent_camera = new Intent(
                                        "android.media.action.IMAGE_CAPTURE");
                                intent_camera.putExtra(MediaStore.EXTRA_OUTPUT,
                                        getImageUri());
                                intent_camera.putExtra(
                                        MediaStore.EXTRA_VIDEO_QUALITY, 0);
                                startActivityForResult(intent_camera,
                                        CAMERA_REQUEST_CODE);
                            } else {
                                Toast.makeText(MainActivity.this, "请插入sd卡",
                                        Toast.LENGTH_SHORT).show();
                            }
                            break;
                        case 1:
                            Intent intent_gallery = new Intent(
                                    Intent.ACTION_PICK,
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent_gallery
                                    .setDataAndType(
                                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                            "image/*");
                            startActivityForResult(intent_gallery,
                                    PICK_REQUEST_CODE);
                            break;
                        }
                    }
                }).show();
    }

    // 在从拍照或者图片啼选择后返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode) {
            case PICK_REQUEST_CODE:
                // 从图片啼选择图片后,直接返回的是uri,然后对通过uri取得图片,进行剪切;
                startPhotoZoom(data.getData());

                break;
            case CAMERA_REQUEST_CODE:
                // 首先判断sd卡是否挂载;
                if (BitmapUtils.isSdcardExisting()) {
                    startPhotoZoom(getImageUri());
                } else {
                    Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片!",
                            Toast.LENGTH_LONG).show();
                }
                break;
            // 启动剪切图片;
            case ZOOM_REQUEST_CODE:
                if (data != null) {
                    showImage(data);
                }
                break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 对图片进行剪切;
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, ZOOM_REQUEST_CODE);
    }

    // 最张显示图片;但是在实际中,在进入activity中要判断sd卡中是否有图片,如果有图片要首先显示图片。
    // 把图片保存到本地,并且上传给服务器;
    private void showImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Bitmap photo_round = BitmapUtils.getRoundedCornerBitmap(photo,
                    10.0f);
            // saveServer();保存到服务器;
            // saveSD();保存到sd卡;
            // 显示在界面中;
            BitmapUtils.saveToSDBitmap(MainActivity.this, "icon.png",
                    photo_round);
            iv_icon.setImageBitmap(photo_round);

        }
    }

    private Uri getImageUri() {
        return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME));
    }
}

工具类代码

package com.example.photodemo;

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

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class BitmapUtils {
    private static String sdState = Environment.getExternalStorageState();
    private static String path = Environment.getExternalStorageDirectory()
            .toString();
    public static final String PHTOT_NAME = "/PHOTO";

    /**
     * 把图片保存到sd卡中,保存的路径为storage/PHOTO;
     * 
     * @param bitmap
     * @param imageName
     */
    public static void saveBitmap(Bitmap bitmap, String imageName) {
        File file;
        File PicName;
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {
            // 获得sd卡根目录
            file = new File(path + PHTOT_NAME);
            if (!file.exists()) {
                file.mkdirs();
            }
            PicName = new File(file, imageName);
            try {
                if (!PicName.exists()) {
                    PicName.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(PicName);
                if (PicName.getName().endsWith(".png")) {
                    bitmap.compress(CompressFormat.PNG, 70, fos);
                } else if (PicName.getName().endsWith(".jpg")) {
                    bitmap.compress(CompressFormat.JPEG, 70, fos);
                }
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从sd卡中取出图片;
     * 
     * @param imageName
     * @return
     */
    public static Bitmap getBitmap(String imageName) {
        Bitmap bitmap = null;
        File imagePic;
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {

            imagePic = new File(path + PHTOT_NAME, imageName);
            if (imagePic.exists()) {
                try {
                    bitmap = BitmapFactory.decodeStream(new FileInputStream(
                            imagePic));
                } catch (FileNotFoundException e) {
                    // e.printStackTrace();
                }
            }
        }
        return bitmap;
    }

    /**
     * 删除sd卡上的图片;
     * 
     * @param file
     */
    public static void deleteFile(File file) {
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                }
                // 如果它是一个目录
                else if (file.isDirectory()) {
                    // 声明目录下所有的文件 files[];
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                        deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                    }
                }
                file.delete();
            }
        }
    }

    /**
     * 把文本保存到SDCard/Android/data/你的应用的包名/files/ 目录下,当卸载应用的时候删除;
     * 
     * @param context
     * @param fileName
     * @param text
     */
    public static void savetoSDText(Context context, String fileName,
            String text) {
        // TODO Auto-generated method stub
        File file = context.getExternalFilesDir("/photo");
        try {
            FileOutputStream fos = new FileOutputStream(file + "/" + fileName);
            fos.write(text.getBytes());
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 把图片保存SDCard/Android/data/你的应用的包名/files/ 目录下 当卸载应用的时候删除
     * 
     * @param context
     * @param fileName
     * @param bitmap
     */
    public static void saveToSDBitmap(Context context, String fileName,
            Bitmap bitmap) {
        File file = context.getExternalFilesDir("/photo");
        try {
            FileOutputStream fos = new FileOutputStream(file + "/" + fileName);
            bitmap.compress(CompressFormat.PNG, 75, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 得到圆角图片; bitmap:传入图片 roundPx :传入显示的圆角弧度,一般设置10.0就可以
     */
    private static Bitmap output;

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        if (bitmap != null) {
            output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                    Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(rect);

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
        }
        return output;
    }

    /**
     * 
     * 判断sd卡是否可用;
     * 
     * @return
     */
    public static boolean isSdcardExisting() {
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}

demo下载地址:http://download.csdn.net/detail/androidxiaogang/9284309

2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:111937次
    • 积分:2658
    • 等级:
    • 排名:第14223名
    • 原创:131篇
    • 转载:2篇
    • 译文:3篇
    • 评论:18条