Android图片上传(头像裁切+原图原样)

首先要先写一个类 可以做出PopupWindow

public class PublishSelectPicPopupWindow extends PopupWindow {


    private Button btnHand;
    private Button btnLibrary;
    private Button btnTwocode;
    private Button btnCancel;
    private View mMenuView;

    @SuppressWarnings("deprecation")
    public PublishSelectPicPopupWindow(Activity context,OnClickListener itemsOnClick) {
        super(context);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.publish_dialog, null);
        btnHand = (Button) mMenuView.findViewById(R.id.btn_hand);
        btnLibrary = (Button) mMenuView.findViewById(R.id.btn_library);
        btnCancel = (Button) mMenuView.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dismiss();
            }
        });
        //设置按钮监听
        btnHand.setOnClickListener(itemsOnClick);
        btnLibrary.setOnClickListener(itemsOnClick);
        btnCancel.setOnClickListener(itemsOnClick);
        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.id.pop_layout).getTop();
                int y=(int) event.getY();
                if(event.getAction()==MotionEvent.ACTION_UP){
                    if(y<height){
                        dismiss();
                    }
                }               
                return true;
            }
        });

    }

}

他也需要一个布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pop_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg_pulish"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_hand"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="20dip"

        android:text="拍照"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_library"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="20dip"

        android:text="从相册选择"
        android:textStyle="bold" />



    <Button
        android:id="@+id/btn_cancel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="30dip"
        android:layout_marginBottom="30dp"

        android:text="取消"
        android:textStyle="bold" />

</LinearLayout>

接下来就是在MainActvity中写的了首先是他的布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <Button
        android:id="@+id/button_up"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上传图片"/>
    <ImageView
        android:id="@+id/touxiang"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher_round"/>

</RelativeLayout>
public class MainActivity extends AppCompatActivity {

   /* private final int REQUESTCODE_CUTTING = 1001;
    private final int REQUESTCODE_PICK = 1002;
    private final int REQUESTCODE_TAKE = 1003;*/

    private Button button_up;
    private PublishSelectPicPopupWindow menuWindow;
    private static final String IMAGE_FILE_NAME = "ic_launcher_round.png";
    private ImageView touxiang;
    private File urlpath;   // 图片本地路径
    private static ProgressDialog pd;// 等待进度圈
    //private String imgUrl = "https://www.zhaoapi.cn/file/upload?uid=2809";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_up = findViewById(R.id.button_up);
        touxiang = findViewById(R.id.touxiang);
        button_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 实例化SelectPicPopupWindow
                menuWindow = new PublishSelectPicPopupWindow(MainActivity.this,itemsOnClick);
                // 显示窗口
                menuWindow.showAtLocation(MainActivity.this.findViewById(R.id.button_up),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });
    }



    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_hand:
                    Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    //下面这句指定调用相机拍照后的照片存储的路径
                    takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
                    startActivityForResult(takeIntent, 1000);
                    break;
                case R.id.btn_library:
                    Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
                    // 如果朋友们要限制上传到服务器的图片类型时可以直接写如:"image/jpeg 、 image/png等的类型"
                    pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(pickIntent, 2000);
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case 2000:// 直接从相册获取
                    try {
                        startPhotoZoom(data.getData());
                    } catch (NullPointerException e) {
                        e.printStackTrace();// 用户点击取消操作
                    }
                    break;
                case 1000:// 调用相机拍照
                    File temp = new File(Environment.getExternalStorageDirectory() + "/" + IMAGE_FILE_NAME);
                    startPhotoZoom(Uri.fromFile(temp));
                    break;
                case 3000:// 取得裁剪后的图片
                    if (data != null) {
                        setPicToView(data);
                    }
                    break;
            }

    }

    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            // 取得SDCard图片路径做显示
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(null, photo);
            urlpath = new File(FileUtil.saveFile(MainActivity.this, "temphead.jpg", photo));
            touxiang.setImageDrawable(drawable);

            // 新线程后台上传服务端
            //pd = ProgressDialog.show(MainActivity.this, null, "正在上传图片,请稍候...");

            HashMap<String, String> map = new HashMap<>();
            map.put("uid", "2809");
            //存到服务端
            OkHttp3Util.uploadFile(ApiUtil.UP_TOUXIANG, urlpath, "dash.jpg", map, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("+++", "onFailure: "+e.getMessage());
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    Log.e("---", "onResponse: "+response.body().string() );
                    if (response.isSuccessful()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "此时上传成功!!", Toast.LENGTH_SHORT).show();
                            }
                        });
                        //此时上传成功  获取用户信息
                        OkHttp3Util.doGet("https://www.zhaoapi.cn/user/getUserInfo?uid=2809", new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                String string = response.body().string();
                                final GeRenBean userBean = new Gson().fromJson(string, GeRenBean.class);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        Glide.with(MainActivity.this)

                                                .load(userBean.getData().getIcon()).transform(new GlideCircleTransform(MainActivity.this))
                                                .into(touxiang);
                                        Toast.makeText(MainActivity.this, "上传并且获取成功", Toast.LENGTH_SHORT).show();
                                    }
                                });

                            }
                        });
                    }

                }
            });




        }
    }




    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3000);
    }



    public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
        String fileFullName = "";
        FileOutputStream fos = null;
        String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)
                .format(new Date());
        try {
            String suffix = "";
            if (filePath == null || filePath.trim().length() == 0) {
                filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/";
            }
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File fullFile = new File(filePath, fileName + suffix);
            fileFullName = fullFile.getPath();
            fos = new FileOutputStream(new File(filePath, fileName + suffix));
            fos.write(bytes);
        } catch (Exception e) {
            fileFullName = "";
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    fileFullName = "";
                }
            }
        }
        return fileFullName;
    }
}

最后放上完整的代码!大家上传路径自己搭建啊!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,可以使用系统自带的裁剪工具来对选择的图片进行裁剪。以下是一些基本步骤: 1. 创建一个 Intent 对象,用于启动裁剪工具: ``` Intent intent = new Intent("com.android.camera.action.CROP"); ``` 2. 设置 Intent 的数据和类型: ``` intent.setDataAndType(uri, "image/*"); ``` 其中,uri 表示选择的图片的 Uri。 3. 设置裁剪工具的参数: ``` intent.putExtra("crop", "true"); intent.putExtra("aspectX", aspectX); intent.putExtra("aspectY", aspectY); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("scale", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri); ``` 其中,aspectX 和 aspectY 分别表示裁剪框的宽高比,outputX 和 outputY 分别表示输出图片的宽高(单位为像素),outputUri 表示输出图片的 Uri。 4. 启动裁剪工具: ``` startActivityForResult(intent, REQUEST_CODE_CROP); ``` 5. 在 onActivityResult 方法中获取裁剪后的图片: ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_CROP && resultCode == RESULT_OK) { Bitmap bitmap = BitmapFactory.decodeFile(outputUri.getPath()); imageView.setImageBitmap(bitmap); } } ``` 需要注意的是,裁剪工具并不是所有 Android 系统都支持,有些系统可能没有预装相应的应用程序,因此建议在使用裁剪工具之前先检查系统是否支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值