实现图片上传功能

news/2024/7/10 4:57:56 标签: path, 图片, 位图

首先让你看一下效果图,,是不是有点眼熟

public class ImageUtils {

   /**
    * Save image to the SD card
    *
    * @param photoBitmap
    * @param photoName
    * @param path
    */
   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;
   }

   /**
    * 转换图片成圆形
    *
    * @param bitmap 传入Bitmap对象
    * @return
    */
   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;
   }
}
这是自己创建的一个上传图片的复制使用即可哦
 
下面这个是mainactivity里面设置要写的东西。。粘贴实现即可哦当然没有优化,想要实现自己优化吧,,我个人比较懒就不实现了
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    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;
    private ImageView iv_personal_icon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_personal_icon = (ImageView) findViewById(R.id.iv_personal_icon);
    }

    /**
     * 显示修改头像的对话框
     */
    public void showChoosePicDialog(View v) {
        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: // 拍照
                        takePicture();
                        break;
                }
            }
        });
        builder.create().show();
    }

    private void takePicture() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT >= 23) {
            // 需要申请动态权限
            int check = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }
        Intent openCameraIntent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment
                .getExternalStorageDirectory(), "image.jpg");
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= 24) {
            openCameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            tempUri = FileProvider.getUriForFile(MainActivity.this, "com.lt.uploadpicdemo.fileProvider", file);
        } else {
            tempUri = Uri.fromFile(new File(Environment
                    .getExternalStorageDirectory(), "image.jpg"));
        }
        // 指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    @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;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    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);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Log.d(TAG,"setImageToView:"+photo);
            photo = ImageUtils.toRoundBitmap(photo); // 这个时候的图片已经被处理成圆形的了
            iv_personal_icon.setImageBitmap(photo);
            uploadPic(photo);
        }
    }

    private void uploadPic(Bitmap bitmap) {
        // 上传至服务器
        // ... 可以在这里把Bitmap转换成file,然后得到file的url,做文件上传操作
        // 注意这里得到的图片已经是圆形图片        // bitmap是没有做个圆形处理的,但已经被裁剪了
        String imagePath = ImageUtils.savePhoto(bitmap, Environment
                .getExternalStorageDirectory().getAbsolutePath(), String
                .valueOf(System.currentTimeMillis()));
        Log.e("imagePath", imagePath+"");
        if(imagePath != null){
            // 拿着imagePath上传了
            // ...
            Log.d(TAG,"imagePath:"+imagePath);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else {
            // 没有获取 到权限,从新请求,或者关闭app
            Toast.makeText(this, "需要存储权限", Toast.LENGTH_SHORT).show();
        }
    }
下面这个是自己的要实现的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="com.zfz.shangchuantupian.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#51CA65"
        android:padding="30dp" >

        <ImageView
            android:id="@+id/iv_personal_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:onClick="showChoosePicDialog"
            android:src="@mipmap/default_personal_image" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn_change"
        android:layout_marginTop="6dp"
        android:onClick="showChoosePicDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改头像" >
    </Button>

</LinearLayout>

好了基本的都已经实现了,,是不是运行失败吖,不失败就错了,,,因为你没有添加权限吖,,需要的权限你自己添加吧,很简单的,自己加吧,,


http://www.niftyadmin.cn/n/862114.html

相关文章

Android 图形验证码

首先呢先让你们看一下效果 下面呢其实主要就是一个工具类 public class CodeUtils {private static final char[] CHARS {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,a, b, c, d, e, f, g, h, i, j, k, l, m,n, o, p, q, r, s, t, u, v, w, x, y, z,A, B, C, D, E, F, G, H, I, J, K, L, M…

App版本更新

1.添加依赖&#xff1a; compile org.xutils:xutils:3.5.0 compile com.google.code.gson:gson:2.8.12.初始化xutils public class BaseApplication extends Application {Overridepublic void onCreate() {super.onCreate();x.Ext.init(this);x.Ext.setDebug(BuildConfig.DEBU…

Android MVP架构简单封装

先看一下自己封装项目的基本库结构。 来看看源码吧 BasePresenter.java public abstract class BasePresenter<T> {protected Reference<T> mViewRef;//View接口类型的弱引用public void attachView(T view){mViewRefnew WeakReference<T>(view);//建立关…

Android中获取手机中的联系人信息

1.0、查看系统通讯录的表,表路径&#xff1a;data—>data—>com.android.providers.contacts—>databases—>contacts2.db 1.1、其中重要的表有&#xff1a; raw_contacts表&#xff08;可查看上次通话记录、可获取联系人的id(“contact_id”)&#xff09;&#…

微信小程序实现轮播图

1. 设置数据 我在 pages/test/test.js中添加如下数据 //test.js //获取应用实例 var app getApp() Page({data: {imgUrls: [{link: /pages/index/index,url: http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg}, {link: /pages/logs/logs,url: htt…

MOB短信验证

短信验证是现在很流行的一种验证身份的技术。用户输入手机号&#xff0c;短信验证平台发送验证码至用户手机&#xff0c;用户输入正确的收到的验证码即可验证手机身份。本文介绍引用第三方mob网站的sdk添加进入app实现短信验证功能的教程。 首先在MOB网站注册账户&#xff0c;…

完美友盟分享

第一步&#xff1a; 去友盟官网注册账号&#xff0c;创建一个应用&#xff08;应用名与项目名保持一致&#xff09;&#xff0c;这个详细步骤可参考友盟QQ登录 此次略过&#xff0c; 正文 导入jar包 添加权限 <uses-permission android:name"android.permission.…

Android-使用Android Studio实现第三方QQ登录

现在的第三方登录很普遍如QQ&#xff0c;微博&#xff0c;微信&#xff0c;今天我们就来实现如何接入QQ登录到我们的项目中 要想使用QQ登录我们需要到腾讯开放平台注册账号获取开发者资格地址&#xff1a;(http://open.qq.com) 注册完成后点击我们右上角的管理中心 进入管理…