长传头像

废话不多说直接上代码

Activity代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {



    private ImageView iconurl;
    private TextView tv_gallery;
    private TextView tv_photograph;
    private TextView tv_cancel;
    private View inflate;
    private PopupWindow popupWindow;
    private View view;
    private String mFilePath;
    private Uri photoUri;
    private Uri meuri;


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

初始化布局
    private void initView() {
        view = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
        inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuwindow_layout, null);
        iconurl = (ImageView) findViewById(R.id.iconurl);
        iconurl.setOnClickListener(this);
        tv_gallery = (TextView) inflate.findViewById(R.id.tv_gallery);
        tv_gallery.setOnClickListener(this);
        tv_photograph = (TextView) inflate.findViewById(R.id.tv_photograph);
        tv_photograph.setOnClickListener(this);
        tv_cancel = (TextView) inflate.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(this);
        mFilePath = mFilePath + "/" + "temp.png";// 指定路径


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iconurl:
                popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                popupWindow.setOutsideTouchable(true);
                popupWindow.setTouchable(true);
                popupWindow.setAnimationStyle(R.style.anima);
                popupWindow.showAtLocation(view, Gravity.BOTTOM,0,0);

                break;

     //调用系统图库选择图片
            case R.id.tv_gallery:
                Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
                albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(albumIntent, 1);
                popupWindow.dismiss();


                break;

             //调用系统相机,设置requestCode

            case R.id.tv_photograph:

                Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
                // 传递路径
                photoUri = Uri.fromFile(tempFile);
                meuri = photoUri;
                // cameraIntent.putExtra(MediaStore.ACTION_IMAGE_CAPTURE, photoUri);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, meuri);// 更改系统默认存储路径
                // 下面这句指定调用相机拍照后的照片存储的路径
                startActivityForResult(cameraIntent, 2);


                popupWindow.dismiss();
                break;
            case R.id.tv_cancel:

                popupWindow.dismiss();

                break;
        }

    }

//通过判断requestCode来判断执行什么操作

@Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1){


            if (data!=null){
                clipPhoto(data.getData());

            }

        }else if(requestCode==2){

            clipPhoto(meuri);

        }else if(requestCode==3){
            Bundle bundle = data.getExtras(); // 从data中取出传递回来缩略图的信息,图片质量差,适合传递小图片
            Bitmap bitmap = (Bitmap) bundle.get("data"); // 将data中的信息流解析为Bitmap类型
            iconurl.setImageBitmap(toRoundBitmap(bitmap));

     //这里是我使用的一个工具类,获取拍照和图片裁剪并得到的路径
            String urlpath = FileUtilcll.saveFile(MainActivity.this, Environment.getExternalStorageDirectory().getPath(),
                    getPhotoFileName(), bitmap);
         
            mImgUrls = new ArrayList<>();
            mImgUrls.add(urlpath);
            uploadImg();
        }
    }

//裁剪图片方法,也需要设置requestCode
    public void clipPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例,这里设置的是正方形(长宽比为1:1)
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 2000);
        intent.putExtra("outputY", 2000);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

//画圆的一个方法,把头像设置成圆的。
    public 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;

    }

//获取系统时间设置为图片名字,避免上传多张图片时造成的覆盖现象。
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }


    private List<String> mImgUrls;
    private File tempFile = new File(Environment.getExternalStorageDirectory().getPath(),
            getPhotoFileName());
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");//设置上传图片格式

    private final OkHttpClient client = new OkHttpClient();

//上传图片通过okhttp的post请求上传文件MultipartBody
    private void uploadImg() {

        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        for (int i = 0; i <mImgUrls.size() ; i++) {
            File f=new File(mImgUrls.get(i));
            if (f!=null) {
                builder.addFormDataPart("img", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url("http://172.16.53.15:8080/UploadDemo4/UploadFile")//这里我用的是tomcat地址
                .post(requestBody)//添加请求体
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }


            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                System.out.println("上传照片成功:response = " + response.body().string());
            }
        });


    }

}




//工具类   FileUtilcll

public class FileUtilcll {


    /**
     * 将Bitmap 图片保存到本地路径,并返回路径
     * @param fileName 文件名称
     * @param bitmap   图片
     * @param资源类型,参照 MultimediaContentType 枚举,根据此类型,保存时可自动归类
     */
    public static String saveFile(Context c, String fileName, Bitmap bitmap) {
        return saveFile(c, "", fileName, bitmap);
    }


    public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {
        byte[] bytes = bitmapToBytes(bitmap);
        return saveFile(c, filePath, fileName, bytes);
    }


    public static byte[] bitmapToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }


    public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
        String fileFullName = "";
        FileOutputStream fos = null;
        String dateFolder = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA)
                .format(new Date());
        try {
            String suffix = "";
            if (filePath == null || filePath.trim().length() == 0) {
                filePath = Environment.getExternalStorageDirectory() + "/XiaoCao/" + 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;
    }
}

深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值