android實(shí)現(xiàn)上傳本地圖片到網(wǎng)絡(luò)功能
本文實(shí)例為大家分享了android上傳本地圖片到網(wǎng)絡(luò)的具體代碼,供大家參考,具體內(nèi)容如下
首先這里用到了Okhttp 所以需要一個(gè)依賴:
compile 'com.squareup.okhttp3:okhttp:3.9.0'
xml布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" tools:context="com.bwei.czx.czx10.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/photo"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/camear"/> </LinearLayout>
AndroidManifest.xml中:權(quán)限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
MainActivity中:
oncreat:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.photo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toPhoto(); } }); findViewById(R.id.camear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toCamera(); } }); }
和oncreat同級(jí)的方法:
public void postFile(File file){ // sdcard/dliao/aaa.jpg String path = file.getAbsolutePath() ; String [] split = path.split("\\/"); MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) // file .addFormDataPart("imageFileName",split[split.length-1]) .addFormDataPart("image",split[split.length-1],RequestBody.create(MEDIA_TYPE_PNG,file)) .build(); Request request = new Request.Builder().post(requestBody).url("http://qhb.2dyt.com/Bwei/upload").build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("response = " + response.body().string()); } }); } static final int INTENTFORCAMERA = 1 ; static final int INTENTFORPHOTO = 2 ; public String LocalPhotoName; public String createLocalPhotoName() { LocalPhotoName = System.currentTimeMillis() + "face.jpg"; return LocalPhotoName ; } public void toCamera(){ try { Intent intentNow = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri uri = null ; // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //針對(duì)Android7.0,需要通過(guò)FileProvider封裝過(guò)的路徑,提供給外部調(diào)用 // uri = FileProvider.getUriForFile(UploadPhotoActivity.this, "com.bw.dliao", SDCardUtils.getMyFaceFile(createLocalPhotoName()));//通過(guò)FileProvider創(chuàng)建一個(gè)content類型的Uri,進(jìn)行封裝 // }else { uri = Uri.fromFile(SDCardUtils.getMyFaceFile(createLocalPhotoName())) ; // } intentNow.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intentNow, INTENTFORCAMERA); } catch (Exception e) { e.printStackTrace(); } } /** * 打開(kāi)相冊(cè) */ public void toPhoto(){ try { createLocalPhotoName(); Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT); getAlbum.setType("image/*"); startActivityForResult(getAlbum, INTENTFORPHOTO); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case INTENTFORPHOTO: //相冊(cè) try { // 必須這樣處理,不然在4.4.2手機(jī)上會(huì)出問(wèn)題 Uri originalUri = data.getData(); File f = null; if (originalUri != null) { f = new File(SDCardUtils.photoCacheDir, LocalPhotoName); String[] proj = {MediaStore.Images.Media.DATA}; Cursor actualimagecursor = this.getContentResolver().query(originalUri, proj, null, null, null); if (null == actualimagecursor) { if (originalUri.toString().startsWith("file:")) { File file = new File(originalUri.toString().substring(7, originalUri.toString().length())); if(!file.exists()){ //地址包含中文編碼的地址做utf-8編碼 originalUri = Uri.parse(URLDecoder.decode(originalUri.toString(),"UTF-8")); file = new File(originalUri.toString().substring(7, originalUri.toString().length())); } FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(f); copyStream(inputStream, outputStream); } } else { // 系統(tǒng)圖庫(kù) int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); actualimagecursor.moveToFirst(); String img_path = actualimagecursor.getString(actual_image_column_index); if (img_path == null) { InputStream inputStream = this.getContentResolver().openInputStream(originalUri); FileOutputStream outputStream = new FileOutputStream(f); copyStream(inputStream, outputStream); } else { File file = new File(img_path); FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(f); copyStream(inputStream, outputStream); } } Bitmap bitmap = ImageResizeUtils.resizeImage(f.getAbsolutePath(), 1080); int width = bitmap.getWidth(); int height = bitmap.getHeight(); FileOutputStream fos = new FileOutputStream(f.getAbsolutePath()); if (bitmap != null) { if (bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos)) { fos.close(); fos.flush(); } if (!bitmap.isRecycled()) { bitmap.isRecycled(); } System.out.println("f = " + f.length()); postFile(f); } } } catch (Exception e) { e.printStackTrace(); } break; case INTENTFORCAMERA: // 相機(jī) try { //file 就是拍照完 得到的原始照片 File file = new File(SDCardUtils.photoCacheDir, LocalPhotoName); Bitmap bitmap = ImageResizeUtils.resizeImage(file.getAbsolutePath(), 1080); int width = bitmap.getWidth(); int height = bitmap.getHeight(); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); if (bitmap != null) { if (bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos)) { fos.close(); fos.flush(); } if (!bitmap.isRecycled()) { //通知系統(tǒng) 回收bitmap bitmap.isRecycled(); } System.out.println("f = " + file.length()); postFile(file); } } catch (Exception e) { e.printStackTrace(); } break; } } public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception { try { byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.flush(); } catch (IOException e) { e.printStackTrace(); }finally { if(inputStream != null){ inputStream.close(); } if(outStream != null){ outStream.close(); } } }
ImageResizeUtils中:
package com.bwei.czx.czx10; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static android.graphics.BitmapFactory.decodeFile; /** * Created by czx on 2017/9/27. */ public class ImageResizeUtils { /** * 照片路徑 * 壓縮后 寬度的尺寸 * @param path * @param specifiedWidth */ public static Bitmap resizeImage(String path, int specifiedWidth) throws Exception { Bitmap bitmap = null; FileInputStream inStream = null; File f = new File(path); System.out.println(path); if (!f.exists()) { throw new FileNotFoundException(); } try { inStream = new FileInputStream(f); int degree = readPictureDegree(path); BitmapFactory.Options opt = new BitmapFactory.Options(); //照片不加載到內(nèi)存 只能讀取照片邊框信息 opt.inJustDecodeBounds = true; // 獲取這個(gè)圖片的寬和高 decodeFile(path, opt); // 此時(shí)返回bm為空 int inSampleSize = 1; final int width = opt.outWidth; // width 照片的原始寬度 specifiedWidth 需要壓縮的寬度 // 1000 980 if (width > specifiedWidth) { inSampleSize = (int) (width / (float) specifiedWidth); } // 按照 565 來(lái)采樣 一個(gè)像素占用2個(gè)字節(jié) opt.inPreferredConfig = Bitmap.Config.RGB_565; // 圖片加載到內(nèi)存 opt.inJustDecodeBounds = false; // 等比采樣 opt.inSampleSize = inSampleSize; // opt.inPurgeable = true; // 容易導(dǎo)致內(nèi)存溢出 bitmap = BitmapFactory.decodeStream(inStream, null, opt); // bitmap = BitmapFactory.decodeFile(path, opt); if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { inStream = null; } } if (bitmap == null) { return null; } Matrix m = new Matrix(); if (degree != 0) { //給Matrix 設(shè)置旋轉(zhuǎn)的角度 m.setRotate(degree); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); } float scaleValue = (float) specifiedWidth / bitmap.getWidth(); // 等比壓縮 m.setScale(scaleValue, scaleValue); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); return bitmap; } catch (OutOfMemoryError e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 讀取圖片屬性:旋轉(zhuǎn)的角度 * * @param path 源信息 * 圖片絕對(duì)路徑 * @return degree旋轉(zhuǎn)的角度 */ public static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception { try { byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.flush(); } catch (IOException e) { e.printStackTrace(); }finally { if(inputStream != null){ inputStream.close(); } if(outStream != null){ outStream.close(); } } } }
SDcardutils中:
package com.bwei.czx.czx10; import android.os.Environment; import android.os.StatFs; import java.io.File; import java.io.IOException; /** * Created by czx on 2017/9/27. */ public class SDCardUtils { public static final String DLIAO = "dliao" ; public static File photoCacheDir = SDCardUtils.createCacheDir(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + DLIAO); public static String cacheFileName = "myphototemp.jpg"; public static boolean isSDCardExist() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } public static void delFolder(String folderPath) { try { delAllFile(folderPath); String filePath = folderPath; filePath = filePath.toString(); File myFilePath = new File(filePath); myFilePath.delete(); } catch (Exception e) { e.printStackTrace(); } } public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);// 先刪除文件夾里面的文件 delFolder(path + "/" + tempList[i]);// 再刪除空文件夾 flag = true; } } return flag; } public static boolean deleteOldAllFile(final String path) { try { new Thread(new Runnable() { @Override public void run() { delAllFile(Environment.getExternalStorageDirectory() + File.separator + DLIAO); } }).start(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 給定字符串獲取文件夾 * * @param dirPath * @return 創(chuàng)建的文件夾的完整路徑 */ public static File createCacheDir(String dirPath) { File dir = new File(dirPath);; if(isSDCardExist()){ if (!dir.exists()) { dir.mkdirs(); } } return dir; } public static File createNewFile(File dir, String fileName) { File f = new File(dir, fileName); try { // 出現(xiàn)過(guò)目錄不存在的情況,重新創(chuàng)建 if (!dir.exists()) { dir.mkdirs(); } f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } return f; } public static File getCacheFile() { return createNewFile(photoCacheDir, cacheFileName); } public static File getMyFaceFile(String fileName) { return createNewFile(photoCacheDir, fileName); } /** * 獲取SDCARD剩余存儲(chǔ)空間 * * @return 0 sd已被掛載占用 1 sd卡內(nèi)存不足 2 sd可用 */ public static int getAvailableExternalStorageSize() { if (isSDCardExist()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); long memorySize = availableBlocks * blockSize; if(memorySize < 10*1024*1024){ return 1; }else{ return 2; } } else { return 0; } } }
這樣就可以上傳圖片到網(wǎng)絡(luò)了!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
flutter傳遞值到任意widget(當(dāng)需要widget嵌套使用需要傳遞值的時(shí)候)
這篇文章主要介紹了flutter傳遞值到任意widget(當(dāng)需要widget嵌套使用需要傳遞值的時(shí)候),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07android如何獲取手機(jī)聯(lián)系人的數(shù)據(jù)庫(kù)示例代碼
很多人在做手機(jī)聯(lián)系人的apk時(shí)會(huì)遇到,如何獲取手機(jī)聯(lián)系人數(shù)據(jù)庫(kù)的問(wèn)題,本篇文章主要介紹了android如何獲取手機(jī)聯(lián)系人的數(shù)據(jù)庫(kù)示例代碼,有興趣的可以了解一下。2017-01-01Android中解決EditText放到popupWindow中,原有復(fù)制、粘貼、全選、選擇功能失效問(wèn)題
這篇文章主要介紹了Android中解決EditText放到popupWindow中,原有復(fù)制、粘貼、全選、選擇功能失效問(wèn)題 的相關(guān)資料,需要的朋友可以參考下2016-04-04Android UI設(shè)計(jì)與開(kāi)發(fā)之實(shí)現(xiàn)應(yīng)用程序只啟動(dòng)一次引導(dǎo)界面
這篇文章主要為大家詳細(xì)介紹了Android UI設(shè)計(jì)與開(kāi)發(fā)之實(shí)現(xiàn)應(yīng)用程序只啟動(dòng)一次引導(dǎo)界面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08Kotlin中內(nèi)置函數(shù)的用法和區(qū)別總結(jié)
眾所周知相比Java, Kotlin提供了不少高級(jí)語(yǔ)法特性。對(duì)于一個(gè)Kotlin的初學(xué)者來(lái)說(shuō)經(jīng)常會(huì)寫(xiě)出一些不夠優(yōu)雅的代碼。下面這篇文章主要給大家介紹了關(guān)于Kotlin中內(nèi)置函數(shù)的用法和區(qū)別的相關(guān)資料,需要的朋友可以參考下2018-06-06Android通過(guò)SeekBar調(diào)節(jié)布局背景顏色
這篇文章主要為大家詳細(xì)介紹了Android通過(guò)SeekBar調(diào)節(jié)布局背景顏色,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04