FH_94的博客通过本文主要向大家介绍了android 上传头像等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
工具类:
import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class ImageUtils { public static String savePhoto(Bitmap photoBitmap, String path, String photoName) { String localPath = null; if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } File photoFile = new File(path, photoName + ".png"); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(photoFile); if (photoBitmap != null) { if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) { // 转换完成 localPath = photoFile.getPath(); fileOutputStream.flush(); } } } catch (FileNotFoundException e) { photoFile.delete(); localPath = null; e.printStackTrace(); } catch (IOException e) { photoFile.delete(); localPath = null; e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); fileOutputStream = null; } } catch (IOException e) { e.printStackTrace(); } } } return localPath; } /** * 转换图片成圆形 * * bitmap 传入Bitmap对象 * */ public static Bitmap toRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom; if (width <= height) { roundPx = width / 2; top = 0; bottom = width; left = 0; right = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom); final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom); final RectF rectF = new RectF(dst); 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, src, dst, paint); return output; } }
实现调用:
protected static final int CHOOSE_PICTURE = 0; protected static final int TAKE_PICTURE = 1; private static final int CROP_SMALL_PICTURE = 2; protected static Uri tempUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_info); ButterKnife.bind(this); ivTx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showChoosePicDialog(); } }); presenter.showUserInfo(); fh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } @Override void createPresenter() { presenter = new MyUserInfoPresenter(this,this); } /** * 显示修改头像的对话框 */ protected void showChoosePicDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("设置头像"); String[] items = {"选择本地照片", "拍照"}; builder.setNegativeButton("取消", null); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case CHOOSE_PICTURE: // 选择本地照片 Intent openAlbumIntent = new Intent( Intent.ACTION_GET_CONTENT); openAlbumIntent.setType("image/*"); startActivityForResult(openAlbumIntent, CHOOSE_PICTURE); break; case TAKE_PICTURE: // 拍照 Intent openCameraIntent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); tempUri = Uri.fromFile(new File(Environment .getExternalStorageDirectory(), "image.jpg")); // 指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换 openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri); startActivityForResult(openCameraIntent, TAKE_PICTURE); break; } } }); builder.create().show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { // 如果返回码是可以用的 switch (requestCode) { case TAKE_PICTURE: startPhotoZoom(tempUri); // 开始对图片进行裁剪处理 break; case CHOOSE_PICTURE: startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理 break; case CROP_SMALL_PICTURE: if (data != null) { setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上 } break; } } } /** * 裁剪图片方法实现 */ protected void startPhotoZoom(Uri uri) { if (uri == null) { Log.i("tag", "The uri is not exist."); } tempUri = uri; Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // 设置裁剪 intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY 是裁剪图片宽高 intent.putExtra("outputX", 150); intent.putExtra("outputY", 150); intent.putExtra("return-data", true); startActivityForResult(intent, CROP_SMALL_PICTURE); } /** * 保存裁剪之后的图片数据 * */ protected void setImageToView(Intent data) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); photo = ImageUtils.toRoundBitmap(photo); // 这个时候的图片已经被处理成圆形的了 ivTx.setImageBitmap(photo); setFile(photo); uploadPic(); } } private void setFile(Bitmap photo) { File file=new File("mnt/sdcard/mo.jpg"); try { BufferedOutputStream bout=new BufferedOutputStream(new FileOutputStream(file)); photo.compress(Bitmap.CompressFormat.JPEG,100,bout); bout.flush(); bout.close(); } catch (Exception e) { e.printStackTrace(); } } private void uploadPic() { File img=new File("mnt/sdcard/mo.jpg"); System.out.println(img.getName() + img.toString() + "==========================="); OkHttpClient okHttpClient1 = new OkHttpClient(); MultipartBody.Builder builder1 = new MultipartBody.Builder(); builder1.setType(MultipartBody.FORM); int uid = Coumens.user.getUid(); String token = Coumens.user.getToken(); builder1.addFormDataPart("uid", uid+""); builder1.addFormDataPart("token",token); builder1.addFormDataPart("file", img.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), img)); Request request1 = new Request.Builder().post(builder1.build()).url(Constant.MAIN+Constant.TOUXIANG).build(); okHttpClient1.newCall(request1).enqueue(new Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { System.out.println("++++++++++++Fileure++++++++++++++"); } @Override public void onResponse(okhttp3.Call call, Response response) throws IOException { if (response.isSuccessful()) { System.out.println("++++++++++++Success++++++++++++++"); System.out.println("fileuploadsuccess:" + response.body().string()); } } }); } @Override public void showUserInfo(MyBean mb) { String tx = mb.getData().getIcon() + ""; Log.i("=========tx", "showUserInfo: "+tx); ImageLoader.getInstance().displayImage(tx,ivTx); tvName.setText(mb.getData().getMobile()); } }