头像上传

记得导入OK和拦截器的依赖。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    tools:context=".Fragment.WoDe.TX_touxiang.Tx_Activity">

    <RelativeLayout
        android:id="@+id/reative_01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:padding="20dp"
            android:text="个人信息"
            android:textSize="26sp"
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"    />

        <View
            android:background="#000"
            android:visibility="visible"
            android:layout_height="1dp"
            android:layout_below="@+id/text"
            android:layout_width="match_parent"></View>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/reative_02"
        android:layout_below="@+id/reative_01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:text="头像"
            android:padding="20dp"
            android:textSize="26sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"/>

        <com.facebook.drawee.view.SimpleDraweeView
            android:padding="20dp"
            fresco:roundAsCircle="true"
            android:id="@+id/headPhoto"
            android:layout_width="108dp"
            android:layout_height="108dp"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            fresco:actualImageScaleType="focusCrop"
            fresco:placeholderImageScaleType="fitCenter"
            fresco:placeholderImage="@drawable/app_default"
            fresco:failureImageScaleType="fitCenter"
            fresco:failureImage="@drawable/load_error_image"  />
    </RelativeLayout>
    <View
        android:background="#000"
        android:visibility="visible"
        android:layout_height="1dp"
        android:layout_below="@+id/reative_02"
        android:layout_width="match_parent"></View>

    <RelativeLayout
        android:id="@+id/reative_03"
        android:layout_below="@+id/reative_02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:text="用户名"
            android:padding="20dp"
            android:textSize="26sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"/>

        <TextView
            android:text="用户名"
            android:padding="20dp"
            android:id="@+id/userName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"/>
    </RelativeLayout>
    <View
        android:background="#000"
        android:visibility="visible"
        android:layout_height="1dp"
        android:layout_below="@+id/reative_03"
        android:layout_width="match_parent"></View>

    <RelativeLayout
        android:id="@+id/reative_04"
        android:layout_below="@+id/reative_03"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:text="昵称"
            android:padding="20dp"
            android:textSize="26sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"/>

        <TextView
            android:text="问天"
            android:padding="20dp"
            android:id="@+id/nickName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"/>
    </RelativeLayout>
    <View
        android:id="@+id/view"
        android:background="#000"
        android:visibility="visible"
        android:layout_height="1dp"
        android:layout_below="@+id/reative_04"
        android:layout_width="match_parent"></View>

    <Button
        android:text="退出"
        android:id="@+id/outLogin"
        android:background="#1E90FF"
        android:layout_marginTop="88dp"
        android:layout_below="@+id/view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
package com.example.administrator.jingdong.Fragment.WoDe.TX_touxiang;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.jingdong.R;
import com.example.administrator.jingdong.view.MainFirst;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.File;

public class Tx_Activity extends AppCompatActivity implements View.OnClickListener {


    /**
     * 点击更换头像
     */
    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 SimpleDraweeView headPhoto;
    /**
     * 用户名
     */
    private TextView userName;
    /**
     * 问天
     */
    private TextView nickName;
    /**
     * 退出
     */
    private Button outLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tx_);
        initView();
    }


    /**
     * 显示修改头像的对话框
     */
    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(Tx_Activity.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");

            photo = ImageUtils.toRoundBitmap(photo); // 这个时候的图片已经被处理成圆形的了
            headPhoto.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();
        }
    }

    private void initView() {
        headPhoto = (SimpleDraweeView) findViewById(R.id.headPhoto);
        userName = (TextView) findViewById(R.id.userName);
        nickName = (TextView) findViewById(R.id.nickName);
        outLogin = (Button) findViewById(R.id.outLogin);
        headPhoto.setOnClickListener(this);
        outLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headPhoto:
                showChoosePicDialog(v);
                break;
            case R.id.outLogin:
                Intent intent = new Intent(Tx_Activity.this, MainFirst.class);
                startActivity(intent);
                finish();
                break;
        }
    }
}

ImageUtils

    
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, Bitmap.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(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
VueSpringBoot中的头像上传通常涉及到前端使用Vue.js框架处理用户选择图片,然后通过Ajax或axios发送到Spring Boot后端进行存储。这里是一个简单的步骤概述: 1. **前端Vue.js部分**: - 使用Vue CLI创建项目:`vue create your-project` - 安装必要的依赖,如`vue-file-loader`或`axios`用于文件上传。 ```bash npm install vue-file-loader axios ``` 2. **组件中头像上传**: - 在组件模板中,创建一个`<input type="file">`让用户选择图片。 ```html <input type="file" @change="uploadAvatar" /> ``` - 在`methods`中定义`uploadAvatar`方法,接收`event`参数,读取选中的文件。 ```javascript methods: { uploadAvatar(e) { const file = e.target.files; // 对文件进行预处理(如压缩、裁剪),然后调用上传接口 this.upload(file); }, upload(file) { const formData = new FormData(); formData.append('avatar', file); axios.post('/api/avatar', formData, {headers: {'Content-Type': 'multipart/form-data'}}) .then(response => { // 处理上传成功后的逻辑,比如更新用户头像URL }) .catch(error => { // 处理错误 }); } } ``` 3. **后端Spring Boot处理**: - 创建一个API接口,例如`/api/avatar`,接收上传的文件并保存到服务器。 - 可能会用到`MultipartFile`处理文件,并将其保存到数据库或存储服务(如Amazon S3或Spring Cloud Storage)。 4. **安全性和优化**: - 验证上传文件类型和大小,防止恶意文件。 - 使用HTTPS保证数据传输安全。 - 分页或限流处理,避免单个用户同时上传大量图片导致性能问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值