• 团队冲刺(八)


    一、认领任务

    今天继续昨天未完成的头像修改和访问图片的操作,实现覆盖掉原来的头像,并修改后刷新。

    二、任务完成时间估算

    页面布局 2h
    从数据库提取 5h

    前端的实现:

    上传图片的Activity

    package com.example.myapplication5;
    
    import android.Manifest;
    import android.annotation.SuppressLint;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Build;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.util.Base64;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    import com.loopj.android.http.RequestParams;
    
    import java.io.ByteArrayOutputStream;
    
    import cz.msebera.android.httpclient.Header;
    
    @SuppressLint("NewApi")
    public class UploadActivity extends AppCompatActivity {
    
        private  String name;
        private ProgressDialog prgDialog;
        private Button button,button1,button8;
        private int RESULT_LOAD_IMG = 1;
        private RequestParams params = new RequestParams();
        private String encodedString;
        private Bitmap bitmap;
        private String imgPath;
        private EditText editTextName;
        private ImageButton imageButton;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_upload);
            Intent intent = getIntent();
            final String user = intent.getStringExtra("name");
            System.out.println("涛涛涛涛1");
            System.out.println(user);
            System.out.println("涛涛涛涛1");
            prgDialog= new ProgressDialog(this);
            prgDialog.setCancelable(false);
            button = findViewById(R.id.choose_image);
            button1 = findViewById(R.id.upload_image);
    
            imageButton = findViewById(R.id.imageButton20);
            imageButton.setImageResource(R.drawable.back);
            imageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   UploadActivity.this.finish();
                }
            });
            editTextName = (EditText) findViewById(R.id.editText);
            editTextName.setText(user);
            button8.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(UploadActivity.this, MainActivity.class);
    //                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//刷新
                    intent.putExtra("key",user);
                    startActivity(intent);// 开始界面的跳转函数容
                }
            });
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    loadImage();
                }
            });
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    uploadImage();
                }
            });
        }
    
    
        public void loadImage() {
            if (Build.VERSION.SDK_INT >= 23) {
                int REQUEST_CODE_CONTACT = 101;
                String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                //验证是否许可权限
                for (String str : permissions) {
                    if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                        //申请权限
                        this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        return;
                    }
                }
            }
            //这里就写了从相册中选择图片,相机拍照的就略过了
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
        }
    
        //当图片被选中的返回结果
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            try {
                if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
    
    
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    
                    // 获取游标
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
    
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imgPath = cursor.getString(columnIndex);
                    cursor.close();
                    ImageView imgView = (ImageView) findViewById(R.id.imageView);
                    imgView.setImageBitmap(BitmapFactory.decodeFile(imgPath));
                } else {
                    Toast.makeText(this, "You haven't picked Image",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
            }
        }
    
        //开始上传图片
        private void uploadImage() {
            if (imgPath != null && !imgPath.isEmpty()) {
                prgDialog.setMessage("Converting Image to Binary Data");
                prgDialog.show();
                encodeImagetoString();
            } else {
                Toast.makeText(getApplicationContext(), "You must select image from gallery before you try to upload",
                        Toast.LENGTH_LONG).show();
            }
        }
    
    
        public void encodeImagetoString() {
            new AsyncTask<Void, Void, String>() {
    
                protected void onPreExecute() {
    
                };
    
                @Override
                protected String doInBackground(Void... params) {
                    BitmapFactory.Options options = null;
                    options = new BitmapFactory.Options();
                    options.inSampleSize = 3;
                    bitmap = BitmapFactory.decodeFile(imgPath,
                            options);
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    // 压缩图片
                    bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
                    byte[] byte_arr = stream.toByteArray();
                    // Base64图片转码为String
                    encodedString = Base64.encodeToString(byte_arr, 0);
                    return "";
                }
    
                @Override
                protected void onPostExecute(String msg) {
                    prgDialog.setMessage("Calling Upload");
                    // 将转换后的图片添加到上传的参数中
                    params.put("image", encodedString);
                    params.put("filename", editTextName.getText().toString());
                    // 上传图片
                    imageUpload();
                }
            }.execute(null, null, null);
        }
    
        public void imageUpload() {
            prgDialog.setMessage("Invoking JSP");
            String url = "http://120.79.40.20/testhttp/uploadimg.jsp";
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, org.apache.http.Header[] headers, byte[] bytes) {
                    prgDialog.hide();
                    Toast.makeText(getApplicationContext(), "upload success", Toast.LENGTH_LONG).show();
                }
                @Override
                public void onFailure(int i, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {
                    prgDialog.hide();
                    if (i == 404) {
                        Toast.makeText(getApplicationContext(),
                                "Requested resource not found", Toast.LENGTH_LONG).show();
                    }
                    // 当 Http 响应码'500'
                    else if ( i== 500) {
                        Toast.makeText(getApplicationContext(),
                                "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }
                    // 当 Http 响应码 404, 500
                    else {
                        Toast.makeText(
                                getApplicationContext(), "Error Occured n Most Common Error: n1. Device " +
                                        "not connected to Internetn2. Web App is not deployed in App servern3." +
                                        " App server is not runningn HTTP Status code : "
                                        + i, Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (prgDialog != null) {
                prgDialog .dismiss();
            }
        }
    }

    后端接受并保存图片:

    jsp

    <%@page import="com.test.util.UploadImage"%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
     <title>图片上传</title>
    </head>
    <body>
    <%
     String imgEncodedStr = request.getParameter("image");
     String fileName = request.getParameter("filename");
     System.out.println("Filename: "+ fileName);
     if(imgEncodedStr != null){
          UploadImage.convertStringtoImage(imgEncodedStr, fileName);
      out.print("Image upload complete, Please check your directory");
     } else{
      out.print("Image is empty");
     }
    %>
    </body>
    </html>

    UploadImage工具类

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.apache.tomcat.util.codec.binary.Base64;
    
    public class UploadImage {
         public static void convertStringtoImage(String encodedImageStr, String fileName) {
          try {
           // Base64解码图片
           byte[] imageByteArray = Base64.decodeBase64(encodedImageStr);
           File file = new File("C:/Program Files/Java/apache-tomcat-8.0.20/fileService/images/" + fileName+".jpg");
           //判断是否存在
           if (file.exists()) {
            System.out.println("file exists");
            file.delete();//存在就删掉再创建
            FileOutputStream imageOutFile = new FileOutputStream("C:/Program Files/Java/apache-tomcat-8.0.20/fileService/images/" + fileName+".jpg");//E:/java web/apache-tomcat-8.0.20/fileService/images/
               imageOutFile.write(imageByteArray);
               imageOutFile.close();
           }else {
               FileOutputStream imageOutFile = new FileOutputStream("C:/Program Files/Java/apache-tomcat-8.0.20/fileService/images/" + fileName+".jpg");//E:/java web/apache-tomcat-8.0.20/fileService/images/
               imageOutFile.write(imageByteArray);
               imageOutFile.close();
           }
           System.out.println("Image Successfully Stored");
          } catch (FileNotFoundException fnfe) {
           System.out.println("Image Path not found" + fnfe);
          } catch (IOException ioe) {
           System.out.println("Exception while converting the Image " + ioe);
          }
         }
        }

    保存到tomcat服务器并刷新。

    下面是访问头像的部分代码:

    class MyHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
    //            ImageView imageView = (ImageView)ly4.findViewById(R.id.imageView2);
    //            imageView.setImageBitmap((Bitmap)msg.obj);
                imageButton11 = (ImageButton)ly4.findViewById(R.id.imageButton11);
                imageButton11.setImageBitmap((Bitmap)msg.obj);
    
            }
        }
    
               new Thread(new Runnable() {
                    @Override
                    public void run() {
    
                        try {
                            //http://10.0.2.2:8080/system/fileService/images/admin.jpg   http://localhost:8080/system/fileService/images/admin.jpg
                            String path = "http://120.79.40.20/system/fileService/images/" + name + ".jpg";//String path = "http://120.79.40.20/system/fileService/images/hua.jpg";
                            //2:把网址封装为一个URL对象
                            URL url = new URL(path);
                            //3:获取客户端和服务器的连接对象,此时还没有建立连接
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            //4:初始化连接对象
                            conn.setRequestMethod("GET");
                            //设置连接超时
                            conn.setConnectTimeout(8000);
                            //设置读取超时
                            conn.setReadTimeout(8000);
                            //5:发生请求,与服务器建立连接
                            conn.connect();
                            //如果响应码为200,说明请求成功
                            if (conn.getResponseCode() == 200) {
                                //获取服务器响应头中的流
                                InputStream is = conn.getInputStream();
                                //读取流里的数据,构建成bitmap位图
                                Bitmap bm = BitmapFactory.decodeStream(is);
                                Message msg = new Message();
                                msg.obj = bm;
                                handler1.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

    以上就能实现头像模块的功能了。

  • 相关阅读:
    数据科学面试应关注的6个要点
    Python3.9的7个特性
    一种超参数优化技术-Hyperopt
    梯度下降算法在机器学习中的工作原理
    MQ(消息队列)功能介绍
    D. The Number of Pairs 数学
    F. Triangular Paths 思维
    D. XOR-gun 思维和 + 前缀
    C. Basic Diplomacy 思维
    D. Playlist 思维
  • 原文地址:https://www.cnblogs.com/a155-/p/12791263.html
Copyright © 2020-2023  润新知