diff --git a/src/CameraAlbumTest/.gitignore b/src/CameraAlbumTest/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/src/CameraAlbumTest/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/src/CameraAlbumTest/.idea/.gitignore b/src/CameraAlbumTest/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/src/CameraAlbumTest/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/src/CameraAlbumTest/.idea/compiler.xml b/src/CameraAlbumTest/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/src/CameraAlbumTest/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/CameraAlbumTest/.idea/gradle.xml b/src/CameraAlbumTest/.idea/gradle.xml new file mode 100644 index 0000000..40d01a4 --- /dev/null +++ b/src/CameraAlbumTest/.idea/gradle.xml @@ -0,0 +1,21 @@ + + + + + + + \ No newline at end of file diff --git a/src/CameraAlbumTest/.idea/jarRepositories.xml b/src/CameraAlbumTest/.idea/jarRepositories.xml new file mode 100644 index 0000000..0380d8d --- /dev/null +++ b/src/CameraAlbumTest/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/CameraAlbumTest/.idea/misc.xml b/src/CameraAlbumTest/.idea/misc.xml new file mode 100644 index 0000000..6199cc2 --- /dev/null +++ b/src/CameraAlbumTest/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/src/CameraAlbumTest/.idea/runConfigurations.xml b/src/CameraAlbumTest/.idea/runConfigurations.xml new file mode 100644 index 0000000..797acea --- /dev/null +++ b/src/CameraAlbumTest/.idea/runConfigurations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/src/CameraAlbumTest/app/.gitignore b/src/CameraAlbumTest/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/src/CameraAlbumTest/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/src/CameraAlbumTest/app/build.gradle b/src/CameraAlbumTest/app/build.gradle new file mode 100644 index 0000000..70680ea --- /dev/null +++ b/src/CameraAlbumTest/app/build.gradle @@ -0,0 +1,48 @@ +plugins { + id 'com.android.application' +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.2" + + defaultConfig { + applicationId "com.example.cameraalbumtest" + minSdkVersion 19 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.2.0' + implementation 'com.google.android.material:material:1.2.1' + implementation 'com.google.code.gson:gson:2.8.8' + implementation 'androidx.constraintlayout:constraintlayout:2.0.1' +// implementation project(path: ':opencv') +// implementation files('libs\\aip-java-sdk-4.16.16.jar') +// implementation files('libs\\json-20160810.jar') +// implementation files('libs\\slf4j-api-1.7.25.jar') +// implementation files('libs\\slf4j-simple-1.7.25.jar') + testImplementation 'junit:junit:4.+' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + + + +} \ No newline at end of file diff --git a/src/CameraAlbumTest/app/libs/aip-java-sdk-4.16.16.jar b/src/CameraAlbumTest/app/libs/aip-java-sdk-4.16.16.jar new file mode 100644 index 0000000..ac8f755 Binary files /dev/null and b/src/CameraAlbumTest/app/libs/aip-java-sdk-4.16.16.jar differ diff --git a/src/CameraAlbumTest/app/libs/json-20160810.jar b/src/CameraAlbumTest/app/libs/json-20160810.jar new file mode 100644 index 0000000..a90e448 Binary files /dev/null and b/src/CameraAlbumTest/app/libs/json-20160810.jar differ diff --git a/src/CameraAlbumTest/app/libs/slf4j-api-1.7.25.jar b/src/CameraAlbumTest/app/libs/slf4j-api-1.7.25.jar new file mode 100644 index 0000000..0143c09 Binary files /dev/null and b/src/CameraAlbumTest/app/libs/slf4j-api-1.7.25.jar differ diff --git a/src/CameraAlbumTest/app/libs/slf4j-simple-1.7.25.jar b/src/CameraAlbumTest/app/libs/slf4j-simple-1.7.25.jar new file mode 100644 index 0000000..a7260f3 Binary files /dev/null and b/src/CameraAlbumTest/app/libs/slf4j-simple-1.7.25.jar differ diff --git a/src/CameraAlbumTest/app/proguard-rules.pro b/src/CameraAlbumTest/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/src/CameraAlbumTest/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/src/CameraAlbumTest/app/src/androidTest/java/com/example/cameraalbumtest/ExampleInstrumentedTest.java b/src/CameraAlbumTest/app/src/androidTest/java/com/example/cameraalbumtest/ExampleInstrumentedTest.java new file mode 100644 index 0000000..46df79d --- /dev/null +++ b/src/CameraAlbumTest/app/src/androidTest/java/com/example/cameraalbumtest/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.example.cameraalbumtest; + +import android.content.Context; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.example.cameraalbumtest", appContext.getPackageName()); + } +} \ No newline at end of file diff --git a/src/CameraAlbumTest/app/src/main/AndroidManifest.xml b/src/CameraAlbumTest/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..01a9cb4 --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/AndroidManifest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/AuthService.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/AuthService.java new file mode 100644 index 0000000..60b832c --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/AuthService.java @@ -0,0 +1,82 @@ +package com.example.cameraalbumtest; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import java.util.Map; +/** + * 获取token类 + */ +public class AuthService { + + /** + * 获取权限token + * @return 返回示例: + * { + * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567", + * "expires_in": 2592000 + * } + */ + public static String getAuth() { + // 官网获取的 API Key 更新为你注册的 + String clientId = "yqUnPxGfPrzGddQwTMATvPiA"; + // 官网获取的 Secret Key 更新为你注册的 + String clientSecret = "E49juivDUPE6ss36FNOUvyTQa8PR9v1S"; + return getAuth(clientId, clientSecret); + } + + /** + * 获取API访问token + * 该token有一定的有效期,需要自行管理,当失效时需重新获取. + * @param ak - 百度云官网获取的 API Key + * @param sk - 百度云官网获取的 Securet Key + * @return assess_token 示例: + * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567" + */ + public static String getAuth(String ak, String sk) { + // 获取token地址 + 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=" + ak + // 3. 官网获取的 Secret Key + + "&client_secret=" + sk; + try { + URL realUrl = new URL(getAccessTokenUrl); + // 打开和URL之间的连接 + HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + // 获取所有响应头字段 + Map> 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); + String access_token = jsonObject.getString("access_token"); + return access_token; + } catch (Exception e) { + System.err.printf("获取token失败!"); + e.printStackTrace(System.err); + } + return null; + } + +} \ No newline at end of file diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/Base64Util.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/Base64Util.java new file mode 100644 index 0000000..24131ab --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/Base64Util.java @@ -0,0 +1,65 @@ +package com.example.cameraalbumtest; + +/** + * Base64 工具类 + */ +public class Base64Util { + private static final char last2byte = (char) Integer.parseInt("00000011", 2); + private static final char last4byte = (char) Integer.parseInt("00001111", 2); + private static final char last6byte = (char) Integer.parseInt("00111111", 2); + private static final char lead6byte = (char) Integer.parseInt("11111100", 2); + private static final char lead4byte = (char) Integer.parseInt("11110000", 2); + private static final char lead2byte = (char) Integer.parseInt("11000000", 2); + private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; + + public Base64Util() { + } + + public static String encode(byte[] from) { + StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); + int num = 0; + char currentByte = 0; + + int i; + for (i = 0; i < from.length; ++i) { + for (num %= 8; num < 8; num += 6) { + switch (num) { + case 0: + currentByte = (char) (from[i] & lead6byte); + currentByte = (char) (currentByte >>> 2); + case 1: + case 3: + case 5: + default: + break; + case 2: + currentByte = (char) (from[i] & last6byte); + break; + case 4: + currentByte = (char) (from[i] & last4byte); + currentByte = (char) (currentByte << 2); + if (i + 1 < from.length) { + currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); + } + break; + case 6: + currentByte = (char) (from[i] & last2byte); + currentByte = (char) (currentByte << 4); + if (i + 1 < from.length) { + currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); + } + } + + to.append(encodeTable[currentByte]); + } + } + + if (to.length() % 4 != 0) { + for (i = 4 - to.length() % 4; i > 0; --i) { + to.append("="); + } + } + + return to.toString(); + } +} diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/CameraActivity.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/CameraActivity.java new file mode 100644 index 0000000..82df42f --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/CameraActivity.java @@ -0,0 +1,177 @@ +package com.example.cameraalbumtest; + +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.hardware.Camera; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.util.Log; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import android.widget.Button; +import android.widget.Toast; + +import androidx.appcompat.app.AppCompatActivity; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback { + private Camera mCamera; + private SurfaceView mSurfaceView; + private SurfaceHolder mSurfaceHolder; + private Uri imageUri; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.camera); + mSurfaceView = findViewById(R.id.surfaceView); + mSurfaceHolder = mSurfaceView.getHolder(); + mSurfaceHolder.addCallback(this); + + Button takePhoto = (Button) findViewById(R.id.take_photo); + takePhoto.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + takePhoto(); + } + }); + } + + @Override + public void surfaceCreated(SurfaceHolder holder) { + // 在surfaceCreated回调中打开相机 + openCamera(); + } + + @Override + public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + // 在surfaceChanged回调中设置相机参数和开始预览 + setupCamera(width, height); + startPreview(); + } + + @Override + public void surfaceDestroyed(SurfaceHolder holder) { + // 在surfaceDestroyed回调中释放相机资源 + releaseCamera(); + } + + private void openCamera() { + try { + mCamera = Camera.open(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void setupCamera(int width, int height) { + if (mCamera != null) { + try { + Camera.Parameters parameters = mCamera.getParameters(); + // 设置相机参数,例如对焦模式、预览大小等 + // ... + mCamera.setParameters(parameters); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + private void startPreview() { + if (mCamera != null && mSurfaceHolder.getSurface() != null) { + try { + mCamera.setPreviewDisplay(mSurfaceHolder); + mCamera.startPreview(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + private void releaseCamera() { + if (mCamera != null) { + mCamera.stopPreview(); + mCamera.release(); + mCamera = null; + } + } + private void takePhoto() { + if (mCamera != null) { + mCamera.takePicture(null, null, new Camera.PictureCallback() { + @Override + public void onPictureTaken(byte[] data, Camera camera) { + // 在这里处理拍照后的照片 + + //人脸识别得到结果 + String ret = FaceRecognition.FaceRecognition(data); + Log.d("ret",ret); + + //保存人脸库方法 + File storageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "YourDirectoryName"); + if (!storageDir.exists()) { + storageDir.mkdirs(); + } + +// Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); +// faceRecognition.detectFaces(bitmap, new FaceDetectionListener() { +// @Override +// public void onFaceDetected(boolean hasFace) { +// // 处理人脸检测结果 +// if (hasFace) { +// // 有人脸 +// } else { +// // 无人脸 +// Toast.makeText(CameraActivity.this, "未检测到人脸,请重新拍照", Toast.LENGTH_SHORT).show(); +// } +// } +// }); + + savePhoto(data); + startPreview(); // 拍照完成后重新启动预览 + } + }); + } + } + + private void savePhoto(byte[] data) { + OutputStream outputStream = null; + try { + File cacheDir = getCacheDir(); // 获取应用的缓存目录 + File imagePath = new File(cacheDir, "output_image.jpg"); // 在缓存目录下创建文件 + imageUri = Uri.fromFile(imagePath); // 将文件路径转换为Uri + + Log.d("path",imageUri.toString()); + // 创建一个文件输出流,指定保存路径 + outputStream = new FileOutputStream(imageUri.getPath()); + // 将字节数组写入文件输出流 + outputStream.write(data); + // 刷新输出流 + outputStream.flush(); + // 保存成功,可以进行相应的提示或其他处理 + Toast.makeText(this, "照片保存成功", Toast.LENGTH_SHORT).show(); + } catch (IOException e) { + e.printStackTrace(); + // 保存失败,可以进行相应的提示或其他处理 + Toast.makeText(this, "照片保存失败", Toast.LENGTH_SHORT).show(); + } finally { + // 关闭输出流 + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + +} + diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/FaceRecognition.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/FaceRecognition.java new file mode 100644 index 0000000..fe3c91c --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/FaceRecognition.java @@ -0,0 +1,60 @@ +package com.example.cameraalbumtest; + +import com.example.cameraalbumtest.HttpUtil; +import com.example.cameraalbumtest.GsonUtils; +import com.example.cameraalbumtest.FileUtil; + +import java.util.*; + +/** + * 人脸对比 + */ +public class FaceRecognition { + + /** + * 重要提示代码中所需工具类 + * FileUtil,Base64Util,HttpUtil,GsonUtils请从 + * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 + * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 + * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 + * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 + * 下载 + */ + public static String FaceRecognition(byte[] data) { + // 请求url + String url = "https://aip.baidubce.com/rest/2.0/face/v3/match"; + try { + List> imageList = new ArrayList<>(); + + // 第一张照片 + Map image1 = new HashMap<>(); + image1.put("image", Base64Util.encode(data)); + image1.put("image_type", "BASE64"); + image1.put("face_type", "LIVE"); + + // 人脸库的照片 + String imagePath = "C:\\Users\\admin\\Desktop"; // 图片文件的路径 + Map image2 = new HashMap<>(); + image2.put("image", Base64Util.encode(FileUtil.readFileByBytes(imagePath))); + image2.put("image_type", "BASE64"); + image2.put("face_type", "LIVE"); + + // 将元素添加到列表 + imageList.add(image1); + imageList.add(image2); + + //将两张图片转为jason格式发送出去 + String param = GsonUtils.toJson(imageList); + + // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 + String accessToken = AuthService.getAuth(); + + String result = HttpUtil.post(url, accessToken, "application/json", param); + System.out.println(result); + return result; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} \ No newline at end of file diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/FileUtil.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/FileUtil.java new file mode 100644 index 0000000..415e4eb --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/FileUtil.java @@ -0,0 +1,72 @@ +package com.example.cameraalbumtest; + +import java.io.*; + +/** + * 文件读取工具类 + */ +public class FileUtil { + + /** + * 读取文件内容,作为字符串返回 + */ + public static String readFileAsString(String filePath) throws IOException { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } + + if (file.length() > 1024 * 1024 * 1024) { + throw new IOException("File is too large"); + } + + StringBuilder sb = new StringBuilder((int) (file.length())); + // 创建字节输入流 + FileInputStream fis = new FileInputStream(filePath); + // 创建一个长度为10240的Buffer + byte[] bbuf = new byte[10240]; + // 用于保存实际读取的字节数 + int hasRead = 0; + while ( (hasRead = fis.read(bbuf)) > 0 ) { + sb.append(new String(bbuf, 0, hasRead)); + } + fis.close(); + return sb.toString(); + } + + /** + * 根据文件路径读取byte[] 数组 + */ + public static byte[] readFileByBytes(String filePath) throws IOException { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } else { + ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); + BufferedInputStream in = null; + + try { + in = new BufferedInputStream(new FileInputStream(file)); + short bufSize = 1024; + byte[] buffer = new byte[bufSize]; + int len1; + while (-1 != (len1 = in.read(buffer, 0, bufSize))) { + bos.write(buffer, 0, len1); + } + + byte[] var7 = bos.toByteArray(); + return var7; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException var14) { + var14.printStackTrace(); + } + + bos.close(); + } + } + } +} diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/GsonUtils.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/GsonUtils.java new file mode 100644 index 0000000..d489282 --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/GsonUtils.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2017 Baidu, Inc. All Rights Reserved. + */ +package com.example.cameraalbumtest; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +import java.lang.reflect.Type; + +/** + * Json工具类. + */ +public class GsonUtils { + private static Gson gson = new GsonBuilder().create(); + + public static String toJson(Object value) { + return gson.toJson(value); + } + + public static T fromJson(String json, Class classOfT) throws JsonParseException { + return gson.fromJson(json, classOfT); + } + + public static T fromJson(String json, Type typeOfT) throws JsonParseException { + return (T) gson.fromJson(json, typeOfT); + } +} diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/HttpUtil.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/HttpUtil.java new file mode 100644 index 0000000..2054fe4 --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/HttpUtil.java @@ -0,0 +1,77 @@ +package com.example.cameraalbumtest; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import java.util.Map; + +/** + * http 工具类 + */ +public class HttpUtil { + + public static String post(String requestUrl, String accessToken, String params) + throws Exception { + String contentType = "application/x-www-form-urlencoded"; + return HttpUtil.post(requestUrl, accessToken, contentType, params); + } + + public static String post(String requestUrl, String accessToken, String contentType, String params) + throws Exception { + String encoding = "UTF-8"; + if (requestUrl.contains("nlp")) { + encoding = "GBK"; + } + return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding); + } + + public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) + throws Exception { + String url = requestUrl + "?access_token=" + accessToken; + return HttpUtil.postGeneralUrl(url, contentType, params, encoding); + } + + public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) + throws Exception { + URL url = new URL(generalUrl); + // 打开和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> 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; + } + in.close(); + System.err.println("result:" + result); + return result; + } +} diff --git a/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/MainActivity.java b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/MainActivity.java new file mode 100644 index 0000000..bc04411 --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/java/com/example/cameraalbumtest/MainActivity.java @@ -0,0 +1,71 @@ +package com.example.cameraalbumtest; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; + +import android.Manifest; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.hardware.Camera; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.Toast; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + + +public class MainActivity extends AppCompatActivity { + private static final int REQUEST_CAMERA_PERMISSION = 1; + private Uri imageUri; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + Button takePhoto = (Button) findViewById(R.id.start); + takePhoto.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + //相机权限 + requestCameraPermission(); + + Intent intent = new Intent(MainActivity.this, CameraActivity.class); + startActivity(intent); + } + }); + } + private void requestCameraPermission() { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.CAMERA}, + REQUEST_CAMERA_PERMISSION); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + if (requestCode == REQUEST_CAMERA_PERMISSION) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + // 用户授予了相机权限 + } else { + // 用户拒绝了相机权限 + Toast.makeText(this, "相机权限被拒绝", Toast.LENGTH_SHORT).show(); + } + } + } +} diff --git a/src/CameraAlbumTest/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/src/CameraAlbumTest/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/CameraAlbumTest/app/src/main/res/drawable/ic_launcher_background.xml b/src/CameraAlbumTest/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/CameraAlbumTest/app/src/main/res/layout/activity_main.xml b/src/CameraAlbumTest/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..082a5b2 --- /dev/null +++ b/src/CameraAlbumTest/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,11 @@ + + +