• 2021 5 25


    云相册主要功能fragment:

    package com.michael.cloudphotos.Home_Fragment;
    
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Matrix;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ProgressBar;
    import android.widget.TableLayout;
    import android.widget.TableRow;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    
    import com.alibaba.sdk.android.oss.ClientConfiguration;
    import com.alibaba.sdk.android.oss.ClientException;
    import com.alibaba.sdk.android.oss.OSSClient;
    import com.alibaba.sdk.android.oss.ServiceException;
    import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
    import com.alibaba.sdk.android.oss.common.OSSLog;
    import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
    import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
    import com.alibaba.sdk.android.oss.model.GetObjectRequest;
    import com.alibaba.sdk.android.oss.model.GetObjectResult;
    import com.alibaba.sdk.android.oss.model.ObjectMetadata;
    import com.google.android.material.floatingactionbutton.FloatingActionButton;
    import com.luck.picture.lib.PictureSelector;
    import com.luck.picture.lib.config.PictureConfig;
    import com.luck.picture.lib.config.PictureMimeType;
    import com.michael.cloudphotos.R;
    import com.michael.cloudphotos.SQLhelper;
    import com.michael.cloudphotos.baidu.Base64Util;
    import com.michael.cloudphotos.baidu.phototheard;
    import com.michael.cloudphotos.helper;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.List;
    import java.util.Map;
    public class Photo_Album_Fragment extends Fragment {
        public SQLhelper sqLhelper=null;//定义数据库helper全局变量
        public String id="";//定义当前用户全局变量
        public String OSS_ENDPOINT="oss-cn-beijing.aliyuncs.com";//OSS存储对象的OSS_ENDPOINT
        public String ACCESS_ID="LTAI5tGwtCwv84C1qC2c3iu5";//OSS存储对象的ACCESS_ID
        public String ACCESS_KEY="Kd6gmeME6xIFY9unTcdH8gaVYCm4LL";//OSS存储对象的ACCESS_key
        public OSSClient oss;//声明OSSClient对象
        public helper p=null;//定义工具类全局变量
        public String[] photo=null;//全局变量:数据库存储的照片ID,用于在OSS下载照片
        public String[] time=null;//全局变量:读取数据库保存的时间,用于分时间显示图片
        public String token="24.565f4c1e92537c3f1801e6c228f4129a.2592000.1625379682.282335-24274696";//百度API的应用的token,有效期一个月
        public View vi;
        public View vi2;
        ProgressBar progressBar;
        Handler handler_phptoid=new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {           //获取所有照片id的handle
                switch (msg.what) {
                    case 1: {
    //                    Toast.makeText(getContext(),msg.obj.toString(),Toast.LENGTH_SHORT).show();
                        photo=p.getphotoid(msg.obj.toString());
                        p.gettime(id,handler_time);                     //获取照片id后获取日期
                        break;
                    }
                }
            }
        };
        Handler handler_time=new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case 1: {
                        time=p.gettimearray(msg.obj.toString());
                        setphoto();         //获取日期之后可以下载并显示照片
                        break;
                    }
                }
            }
        };
        Handler handler_delete=new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case 1: {
                        refreash(vi2);//刷新界面
                        break;
                    }
                }
            }
        };
        Handler handler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch(msg.what)
                {
                    case 1 : {
                        try {
                            progressBar.setVisibility(View.GONE);
                            Bundle b = msg.getData();
                            String result = b.getString("result");
                            final String photoid = b.getString("photoid");
                            LinearLayout l = vi.findViewById(R.id.linear1);
                            TextView textView = new TextView(getActivity());
                            textView.setText(showinfo(result));
                            textView.setTextSize(15);
                            textView.setPadding(0, 0, 0, 10);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            textView.setLayoutParams(params);
                            l.addView(textView);
                            new AlertDialog.Builder(getActivity())
                                    .setTitle("")//提示框标题
                                    .setView(vi)
                                    .setPositiveButton("确定", null).setNegativeButton("删除", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    p = new helper(sqLhelper);
                                    p.delete(photoid, handler_delete);
                                }
                            }).create().show();
                        }catch (Exception e){}
                    }
                    case 2 :break;
                }
            }
        };
        public String showinfo(String info){///处理图片识别返回的结果
            String Info="";
            if(info!=null) {
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(info);
                    String value = jsonObject.optString("result", null);
                    if(value!=null) {
                        JSONArray arr = new JSONArray(value);
                        for (int i = 0; i < 3; i++) {
                            JSONObject temp = (JSONObject) arr.get(i);
                            Info += "分类:" + temp.getString("root") + ",种类:" + temp.getString("keyword") + "
    匹配度:" + temp.getString("score") + "
    ";
                            info+=temp.getString("keyword")+",";
                        }
                        return Info;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return Info;
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup contanier, Bundle savedInstanceState){
            return inflater.inflate(R.layout.activity_photo__album__fragment,contanier,false);
        }
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            vi2=view;//将view变成全局变量
            FloatingActionButton button=view.findViewById(R.id.open);
            progressBar=view.findViewById(R.id.progress);
    //        getAuth();
            sqLhelper=new SQLhelper(getActivity(),"clouduser",null,1);
            p=new helper(sqLhelper);
            if(p.lastuser()) {
                id=p.lastid();
                p.getphotoid(id,handler_phptoid);
            }
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(p.lastuser()) {
                        PictureSelector.create(getActivity())
                                .openGallery(PictureMimeType.ofImage())
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }else {
                        Toast.makeText(getActivity(),"请登录!",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        public void update(final String photoid, final ImageView imageView)      //下载照片
        {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap b = null;
                    OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(ACCESS_ID, ACCESS_KEY);
                    ClientConfiguration conf = new ClientConfiguration();
                    conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
                    conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
                    conf.setMaxConcurrentRequest(8); // 最大并发请求数,默认5个
                    conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
                    // oss为全局变量,OSS_ENDPOINT是一个OSS区域地址
                    oss = new OSSClient(getContext(), OSS_ENDPOINT, credentialProvider, conf);
                    //构造下载文件请求
                    //objectKey等同于objectName,表示从OSS下载文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg
                        GetObjectRequest get = new GetObjectRequest("sean1246", photoid);
                        //设置下载进度回调
                        get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
                            @Override
                            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                                OSSLog.logDebug("getobj_progress:" + currentSize + "total_size:" + totalSize, false);
                            }
                        });
                        try {
                            // 同步执行下载请求,返回结果
                            GetObjectResult getResult = oss.getObject(get);
                            Log.d("Content-Length是", "" + getResult.getContentLength());
                            // 获取文件输入流
                            InputStream inputStream = getResult.getObjectContent();
                            b = BitmapFactory.decodeStream(inputStream);
                            final Bitmap finalB1 =b;
                            final Bitmap finalB2 = zoomImg(cropBitmap(b),230);
                            getActivity().runOnUiThread(new Runnable() {   //必须在主线程显示照片
                                public void run() {
                                    final phototheard p=new phototheard();
                                    imageView.setImageBitmap(finalB2);
                                    imageView.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            progressBar.setVisibility(View.VISIBLE);
                                            Log.d("长度", String.valueOf(finalB2.getByteCount()/1024/1024)+"兆"+ ",M宽度为" + finalB2.getWidth() + "高度为" + finalB2.getHeight());
                                            LayoutInflater factory = LayoutInflater.from(getActivity());
                                            vi = factory.inflate(R.layout.showinfo, null);
                                            LinearLayout l=vi.findViewById(R.id.linear1);
                                            ImageView imageView1=new ImageView(getContext());
                                            imageView1.setImageBitmap(zoomImg(finalB1,1000));
                                            l.addView(imageView1);
                                            advancedGeneral(finalB2,photoid);
                                        }
                                    });
                                }
                            });
                            ObjectMetadata metadata = getResult.getMetadata();
                            Log.d("ContentType", metadata.getContentType());
                        } catch (ClientException e) {
                            // 本地异常如网络异常等
                            e.printStackTrace();
                        } catch (ServiceException e) {
                            // 服务异常
                            Log.e("RequestId", e.getRequestId());
                            Log.e("ErrorCode", e.getErrorCode());
                            Log.e("HostId", e.getHostId());
                            Log.e("RawMessage", e.getRawMessage());
                        }
                    }
            }).start();
        }
        public static Bitmap zoomImg(Bitmap bm, int newWidth) {//bitmap的缩放
            Bitmap newbm = null;
            if (bm!=null){
                // 获得图片的宽高
                int width = bm.getWidth();
                int height = bm.getHeight();
                // 计算缩放比例
                float scaleWidth = ((float) newWidth) / width;
                // 取得想要缩放的matrix参数
                Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth, scaleWidth);
                // 得到新的图片
                newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
            }
            return newbm;
        }
        public static Bitmap cropBitmap(Bitmap bitmap) {//从中间截取一个正方形
            int w = bitmap.getWidth(); // 得到图片的宽,高
            int h = bitmap.getHeight();
            int cropWidth = w >= h ? h : w;// 裁切后所取的正方形区域边长
            return Bitmap.createBitmap(bitmap, (bitmap.getWidth() - cropWidth) / 2,
                    (bitmap.getHeight() - cropWidth) / 2, cropWidth, cropWidth);
        }
        public void setphoto()   //显示照片
        {
            LinearLayout linearLayout=getView().findViewById(R.id.linear);
            String[] a=null;
    //        updownphoto u=new updownphoto(photo[1].split("\+"),handler_photo);
    //        u.run(getActivity());
            for(int i=0;i<time.length;i++)
            {
                TextView textView = new TextView(getActivity());
                textView.setText(time[i]);
                linearLayout.addView(textView);
                if(i+1<photo.length) {
                    a = photo[i + 1].split("\+");
                    for (int j = 0; j < a.length; j = j + 4) {
                        TableLayout tableLayout = new TableLayout(getActivity());
                        TableRow tableRow = new TableRow(getActivity());
                        tableLayout.addView(tableRow);
                        linearLayout.addView(tableLayout);
                        for (int p = j; p < p + 4; p++) {
                            if (p == a.length) break;
                            ImageView imageView = new ImageView(getActivity());
                            imageView.setPadding(20, 20, 20, 20);
                            tableRow.addView(imageView);
                            update(a[p], imageView);
                        }
                    }
                }else{
                    Toast.makeText(getActivity(),"点击加号上传照片",Toast.LENGTH_SHORT).show();
                }
            }
        }
        public String advancedGeneral(Bitmap bitmap,String photoid) {
            // 请求url
            String url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general";
            try {
                byte[] imgData =BitmapToBytes(bitmap);
                // 本地文件路径
                String imgStr = Base64Util.encode(imgData);
                String imgParam = URLEncoder.encode(imgStr, "UTF-8");
                String param = "image=" + imgParam;
                String result = postGeneralUrl(url, param,token,photoid);
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        private byte[] BitmapToBytes(Bitmap bitmap){
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            return baos.toByteArray();
        }
        public  void  getAuth() {//获取token
            // 获取token地址
            new Thread(){
                @Override
                public void run() {
                    String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
                    String getAccessTokenUrl = authHost
                            // 1. grant_type为固定参数
                            + "grant_type=client_credentials"
                            // 2. 官网获取的 API Key
                            + "&client_id=lHdmbiCGvK7Iu3AOAROGQG3m"
                            // 3. 官网获取的 Secret Key
                            + "&client_secret=PvGGSDSn1DMpGUj1QL6oLY09Sn9akgfy";
                    try {
                        URL realUrl = new URL(getAccessTokenUrl);
                        // 打开和URL之间的连接
                        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
                        connection.setRequestMethod("GET");
                        connection.connect();
                        // 获取所有响应头字段
                        Map<String, List<String>> map = connection.getHeaderFields();
                        // 遍历所有的响应头字段
                        for (String key : map.keySet()) {
                            System.err.println(key + "--->" + map.get(key));
                        }
                        // 定义 BufferedReader输入流来读取URL的响应
                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String result = "";
                        String line;
                        while ((line = in.readLine()) != null) {
                            result += line;
                        }
                        /**
                         * 返回结果示例
                         */
                        System.err.println("result:" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        token= jsonObject.getString("access_token");
                    } catch (Exception e) {
                        System.err.printf("获取token失败!");
                        e.printStackTrace(System.err);
                    }
                }
            }.start();
        }
        public  String postGeneralUrl(final String generalUrl, final String params, final String accessToken,final String photoid) throws Exception {//发送识别请求
            final String[] a = {""};
            new Thread() {
                @Override
                public void run() {
                    try {
                        String contentType = "application/x-www-form-urlencoded";
                        String l = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general" + "?access_token=" + accessToken;
                        String encoding = "UTF-8";
                        if (generalUrl.contains("nlp")) {
                            encoding = "GBK";
                        }
                        URL url = null;
                        url = new URL(l);
                        // 打开和URL之间的连接
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("POST");
                        // 设置通用的请求属性
                        connection.setRequestProperty("Content-Type", contentType);
                        connection.setRequestProperty("Connection", "Keep-Alive");
                        connection.setUseCaches(false);
                        connection.setDoOutput(true);
                        connection.setDoInput(true);
                        // 得到请求的输出流对象
                        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                        out.write(params.getBytes(encoding));
                        out.flush();
                        out.close();
    
                        // 建立实际的连接
                        connection.connect();
                        // 获取所有响应头字段
                        Map<String, List<String>> headers = connection.getHeaderFields();
                        // 遍历所有的响应头字段
                        for (String key : headers.keySet()) {
                            System.err.println(key + "--->" + headers.get(key));
                        }
                        // 定义 BufferedReader输入流来读取URL的响应
                        BufferedReader in = null;
                        in = new BufferedReader(
                                new InputStreamReader(connection.getInputStream(), encoding));
                        String result = "";
                        String getLine;
                        while ((getLine = in.readLine()) != null) {
                            result += getLine;
                            System.err.println("result:" + result);
                            a[0] =result;
                        }
    //                    Message msg=new Message();
    //                    msg.what=1;
    //                    msg.obj=result;
    //                    handler.sendMessage(msg);
                        Message msg = handler.obtainMessage();
                        msg.what=1;
                        //msg.arg1 = 123;//传递整型数据
                        //msg.obj = "asd";传递object类型
                        //利用bundle对象来传值
    
                        Bundle b = new Bundle();
                        b.putString("result", result);
                        b.putString("photoid", photoid);
                        msg.setData(b);
                        msg.sendToTarget();
                        final String p=result;
                        in.close();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            return a[0];
        }
        public void  refreash(View vi)//刷新fragment
        {
            LinearLayout linearLayout=vi.findViewById(R.id.linear);
            linearLayout.removeAllViews();
            p.getphotoid(id,handler_phptoid);
        }
    }
  • 相关阅读:
    php select socket
    php socket获取客户端IP地址
    php长连接
    Socket 深度探究 4 PHP (三)
    Socket 深度探究 4 PHP (二)
    Socket 深度探索 4 PHP (一)
    进阶系列(10)——反射
    ASP.NET MVC5 基础系列(2)——模型绑定
    进阶系列(7)——委托与事件
    ASP.NET MVC5 基础系列(4)——表单和HTML辅助方法
  • 原文地址:https://www.cnblogs.com/fuxw4971/p/14910630.html
Copyright © 2020-2023  润新知