Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Android realize the function of taking pictures, selecting pictures and uploading them?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you Android how to achieve photo selection and upload function, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

First, the way to realize it:

1.Android mobile client, take a picture (or select a picture), and then upload to the server.

two。 The server receives the pictures uploaded by the mobile phone.

Second, the implementation steps:

Project structure:

Activity_main.xml

MainActivity.java

Package com.qingshan.note;import androidx.annotation.NonNull;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat;import android.Manifest;import android.app.AlertDialog;import android.content.ContentValues;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.net.Uri;import android.os.Build;import android.os.Bundle Import android.os.Environment;import android.provider.MediaStore;import android.provider.Settings;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection Import java.net.URL;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button btnPhoto, btnSelect; private Intent intent; private final int CAMERA = 1 role / event enumeration (customizable) private final int CHOOSE = 2 / / event enumeration (customizable) private final String postUrl = "http://qingshanboke.com/Home/AndoridUploadFile";// receives the address of the uploaded picture String photoPath ="; / / the path of the picture to be uploaded is private final int permissionCode = 100 / / permission request code / / permission collection, corresponding to adding configuration / / String [] permissions = new String [] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.INTERNET} in the AndroidManifest.xml file; AlertDialog alertDialog; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main) Use dynamic permission if (Build.VERSION.SDK_INT > = 23) {checkPermission ();} btnPhoto = findViewById (R.id.btnPhoto); btnSelect = findViewById (R.id.btnSelect); btnPhoto.setOnClickListener (this); btnSelect.setOnClickListener (this);} / / check permission private void checkPermission () {List permissionList = new ArrayList (); for (int I = 0; I)

< permissions.length; i++) { if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) { permissionList.add(permissions[i]); } } if (permissionList.size() = Build.VERSION_CODES.N) { try { ContentValues values = new ContentValues(1); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg"); values.put(MediaStore.Images.Media.DATA, photoPath); Uri tempuri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); if (tempuri != null) { intent.putExtra(MediaStore.EXTRA_OUTPUT, tempuri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); } startActivityForResult(intent, CAMERA); } catch (Exception e) { e.printStackTrace(); } } else { intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri uri = Uri.fromFile(file); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); //指定拍照后的存储路径,保存原图 startActivityForResult(intent, CAMERA); } break; //选择按钮事件 case R.id.btnSelect: intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, CHOOSE); break; } } @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { // 调用照相机拍照 case CAMERA: if (resultCode == RESULT_OK) { //对应方法一:图片未保存,需保存文件到本地// Bundle bundle = data.getExtras();// Bitmap bitmap = (Bitmap) bundle.get("data");// String savePath;// String SD_PATH = Environment.getExternalStorageDirectory().getPath() + "/拍照上传示例/";// SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// String fileName = format.format(new Date(System.currentTimeMillis())) + ".JPEG";// if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// savePath = SD_PATH;// } else {// Toast.makeText(MainActivity.this, "保存失败!", Toast.LENGTH_SHORT).show();// return;// }// photoPath = savePath + fileName;// File file = new File(photoPath);// try {// if (!file.exists()) {// file.getParentFile().mkdirs();// file.createNewFile();// }// FileOutputStream stream = new FileOutputStream(file);// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// Toast.makeText(MainActivity.this, "保存成功,位置:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();// } catch (IOException e) {// e.printStackTrace();// } //对应方法二:图片已保存,只需读取就行了 try { FileInputStream stream = new FileInputStream(photoPath); Bitmap bitmap = BitmapFactory.decodeStream(stream); //预览图片 ImageView image = findViewById(R.id.imageView); image.setImageBitmap(bitmap); //上传图片(Android 4.0 之后不能在主线程中请求HTTP请求) File file = new File(photoPath); if (file.exists()) { new Thread(new Runnable() { @Override public void run() { //文本字段(用于验证用户身份) HashMap form = new HashMap(); form.put("username", "zhangqs"); form.put("password", "123456"); //图片字段 HashMap file = new HashMap(); file.put(PathHelper.getFileNameFromPath(photoPath), photoPath); formUpload(postUrl, form, file); } }).start(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } break; // 选择图片库的图片 case CHOOSE: if (resultCode == RESULT_OK) { try { Uri uri = data.getData(); photoPath = PathHelper.getRealPathFromUri(MainActivity.this, uri); Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); //压缩图片 bitmap = scaleBitmap(bitmap, (float) 0.5); //预览图片 ImageView image = findViewById(R.id.imageView); image.setImageBitmap(bitmap); //上传图片(Android 4.0 之后不能在主线程中请求HTTP请求) File file = new File(photoPath); if (file.exists()) { new Thread(new Runnable() { @Override public void run() { //文本字段(用于验证用户身份) HashMap form = new HashMap(); form.put("username", "zhangqs"); form.put("password", "123456"); //图片字段 HashMap file = new HashMap(); file.put(PathHelper.getFileNameFromPath(photoPath), photoPath); formUpload(postUrl, form, file); } }).start(); } } catch (IOException e) { e.printStackTrace(); } } break; } } //压缩图片 public Bitmap scaleBitmap(Bitmap origin, float ratio) { if (origin == null) { return null; } int width = origin.getWidth(); int height = origin.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(ratio, ratio); Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false); return newBM; } //POST 表单提交 @RequiresApi(api = Build.VERSION_CODES.O) public static String formUpload(String posturl, Map textMap, Map fileMap) { String res = ""; HttpURLConnection conn = null; String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符 try { URL url = new URL(posturl); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(30000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); // text if (textMap != null) { StringBuffer buffer = new StringBuffer(); Iterator iter = textMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } buffer.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); buffer.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); buffer.append(inputValue); } out.write(buffer.toString().getBytes()); } // file if (fileMap != null) { Iterator iter = fileMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } File file = new File(inputValue); String filename = file.getName(); String contentType = ""; if (filename.endsWith(".jpg")) { contentType = "image/jpg"; } else if (filename.endsWith(".png")) { contentType = "image/png"; } else if (contentType == null || contentType.equals("")) { contentType = "application/octet-stream"; } StringBuffer buffer = new StringBuffer(); buffer.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); buffer.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n"); buffer.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(buffer.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); } } byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 读取返回数据 StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } res = buffer.toString(); reader.close(); reader = null; } catch (Exception e) { System.out.println("发送POST请求出错。" + posturl); e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); conn = null; } } return res; }} PathHelper.java package com.qingshan.note;import android.annotation.SuppressLint;import android.content.ContentUris;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Build;import android.provider.DocumentsContract;import android.provider.MediaStore;//Android 路径辅助类public class PathHelper { //适配api19以下(不包括api19),根据uri获取图片的绝对路径 public static String getRealPathFromUri(Context context, Uri uri) { int sdkVersion = Build.VERSION.SDK_INT; if (sdkVersion >

= 19) {/ / api > = 19 return getRealPathFromUriAboveApi19 (context, uri);} else {/ / api < 19 return getRealPathFromUriBelowAPI19 (context, uri) }} / * adapts to the following api19 (excluding api19). Get the absolute path of the picture according to the uri * * @ param context context object * @ param uri Uri * @ return. If the picture corresponding to Uri exists, return the absolute path of the picture, otherwise return null * / private static String getRealPathFromUriBelowAPI19 (Context context, Uri uri) {return getDataColumn (context, uri, null, null). } / * adapts to api19 and above. Get the absolute path of the picture according to uri * * @ param context context object * @ param uri Uri * @ return. If the picture corresponding to Uri exists, return the absolute path of the picture, otherwise return null * / @ SuppressLint ("NewApi") private static String getRealPathFromUriAboveApi19 (Context context, Uri uri) {String filePath = null If (DocumentsContract.isDocumentUri (context, uri)) {/ / if it is a document type of uri, process String documentId = DocumentsContract.getDocumentId (uri) through document id; if (isMediaDocument (uri)) {/ / MediaProvider / / use': 'split String id = documentId.split (":") [1]; String selection = MediaStore.Images.Media._ID + "=?"; String [] selectionArgs = {id} FilePath = getDataColumn (context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);} else if (isDownloadsDocument (uri)) {/ / DownloadsProvider Uri contentUri = ContentUris.withAppendedId (Uri.parse ("content://downloads/public_downloads"), Long.valueOf (documentId)); filePath = getDataColumn (context, contentUri, null, null);} else if ("content" .equals IgnoreCase (uri.getScheme () {/ / if it is content type Uri filePath = getDataColumn (context, uri, null, null) } else if ("file" .equals (uri.getScheme () {/ / if it is a Uri of file type, directly get the corresponding path filePath = uri.getPath ();} return filePath;} private static String getDataColumn (Context context, Uri uri, String selection, String [] selectionArgs) {String path = null; String [] projection = new String [] {MediaStore.Images.Media.DATA}; Cursor cursor = null; try {cursor = context.getContentResolver (). Query (uri, projection, selection, selectionArgs, null) If (cursor! = null & & cursor.moveToFirst ()) {int columnIndex = cursor.getColumnIndexOrThrow (projection [0]); path = cursor.getString (columnIndex);}} catch (Exception e) {e.printStackTrace ();} finally {if (cursor! = null) {cursor.close ();} return path;} private static boolean isMediaDocument (Uri uri) {return "com.android.providers.media.documents" .equals (uri.getAuthority ()) } private static boolean isDownloadsDocument (Uri uri) {return "com.android.providers.downloads.documents" .equals (uri.getAuthority ());} / / extract the file name public static String getFileNameFromPath (String path) {int start = path.lastIndexOf ("/"); int end = path.lastIndexOf ("."); if (start! =-1 & & end! =-1) {return path.substring (start + 1, end);} else {return null;}

AndroidManifest.xml

\ res\ xml\ network_security_config.xml

127.0.0.1 192.168.100.192 localhost qingshanboke.com

Server-side receive (asp.net mvc receive)

Public ActionResult AndoridUploadFile () {var userName = Request.Params ["username"]; var password = Request.Params ["password"]; if (string.IsNullOrEmpty (userName) | | string.IsNullOrEmpty (password)) {return Content ("Sorry, wrong username and password!") ;} / / todo: authentication var dir = PathHelper.GetMapPath ("~ / Uploadfiles/" + DateTime.Now.ToString ("yyyy-MM")); if (! Directory.Exists (dir)) {Directory.CreateDirectory (dir);} for (int I = 0; I < Request.Files.Count; iTunes +) {var path = Path.Combine (dir, DateTime.Now.ToString ("yyyyMMddHHmmss") + ".jpg") If (Request.Files [I]! = null) {Request.Files [I] .saveAs (path);} return Content ("{\" isSuccess\ ": true}");}

Matters needing attention

When 1.Android initiates a http request, the default request address is https, and the network-security-config configuration needs to be added to allow the use of http. (see 6.\ res\ xml\ network_security_config.xml above for details)

two。 When initiating a post submission, you often need to do interface identification, submit the text field and the picture field together, and construct the form with "Content-Type" and "multipart/form-data; boundary...".

3. When taking photos, you can only get thumbnails by default, which is not clear enough. If you want to get the original image, you need to pass in the specified save location when taking photos, and you only need to read it in the callback function.

The above is all the contents of the article "how to take pictures, select pictures and upload pictures in Android". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report