本文实例为大家分享了android上传本地图片到网络的具体代码,供大家参考,具体内容如下

首先这里用到了Okhttp 所以需要一个依赖:
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中:权限
<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同级的方法:
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) { //针对Android7.0,需要通过FileProvider封装过的路径,提供给外部调用
// uri = FileProvider.getUriForFile(UploadPhotoActivity.this, "com.bw.dliao", SDCardUtils.getMyFaceFile(createLocalPhotoName()));//通过FileProvider创建一个content类型的Uri,进行封装
// }else {
uri = Uri.fromFile(SDCardUtils.getMyFaceFile(createLocalPhotoName())) ;
// }
intentNow.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intentNow, INTENTFORCAMERA);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 打开相册
*/
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:
//相册
try {
// 必须这样处理,不然在4.4.2手机上会出问题
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 {
// 系统图库
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:
// 相机
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()) {
//通知系统 回收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();
//照片不加载到内存 只能读取照片边框信息
opt.inJustDecodeBounds = true;
// 获取这个图片的宽和高
decodeFile(path, opt); // 此时返回bm为空
int inSampleSize = 1;
final int width = opt.outWidth;
// width 照片的原始宽度 specifiedWidth 需要压缩的宽度
// 1000 980
if (width > specifiedWidth) {
inSampleSize = (int) (width / (float) specifiedWidth);
}
// 按照 565 来采样 一个像素占用2个字节
opt.inPreferredConfig = Bitmap.Config.RGB_565;
// 图片加载到内存
opt.inJustDecodeBounds = false;
// 等比采样
opt.inSampleSize = inSampleSize;
// opt.inPurgeable = true;
// 容易导致内存溢出
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 设置旋转的角度
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;
}
}
/**
* 读取图片属性:旋转的角度
*
* @param path 源信息
* 图片绝对路径
* @return degree旋转的角度
*/
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 创建的文件夹的完整路径
*/
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 {
// 出现过目录不存在的情况,重新创建
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剩余存储空间
*
* @return 0 sd已被挂载占用 1 sd卡内存不足 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;
}
}
}
这样就可以上传图片到网络了!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# android上传本地图片到网络
# android上传图片到网络
# android上传本地图片
# Android中使用GridView实现仿微信图片上传功能(附源代码)
# android递归压缩上传多张图片到七牛的实例代码
# Android上传多张图片的实例代码(RxJava异步分发)
# 浅析Android 快速实现图片压缩与上传功能
# Android将图片上传到php服务器的实例代码
# Android使用OkHttp上传图片的实例代码
# Android OkHttp 结合php 多图片上传实例
# Android实现图片选择上传功能实例
# 加载
# 已被
# 不存在
# 大家分享
# 提供给
# 创建一个
# 上传图片
# 具体内容
# 上会
# 大家多多
# 就可以
# 为空
# 容易导致
# 上传
# 内存不足
# newCall
# upload
# qhb
# enqueue
# Bwei
相关文章:
建站之星备案流程有哪些注意事项?
相亲简历制作网站推荐大全,新相亲大会主持人小萍萍资料?
天河区网站制作公司,广州天河区如何办理身份证?需要什么资料有预约的网站吗?
北京营销型网站制作公司,可以用python做一个营销推广网站吗?
广州营销型建站服务商推荐:技术优势与SEO优化解析
国美网站制作流程,国美电器蒸汽鍋怎么用官方网站?
网站制作企业,网站的banner和导航栏是指什么?
免费制作统计图的网站有哪些,如何看待现如今年轻人买房难的情况?
c++怎么编写动态链接库dll_c++ __declspec(dllexport)导出与调用【方法】
如何通过远程VPS快速搭建个人网站?
学校为何禁止电信移动建设网站?
公司网站建设制作费用,想建设一个属于自己的企业网站,该如何去做?
已有域名和空间,如何快速搭建网站?
,巨量百应是干嘛的?
美食网站链接制作教程视频,哪个教做美食的网站比较专业点?
如何零成本快速生成个人自助网站?
建站之星后台搭建步骤解析:模板选择与产品管理实操指南
网站专业制作公司有哪些,做一个公司网站要多少钱?
阿里云高弹*务器配置方案|支持分布式架构与多节点部署
高端建站三要素:定制模板、企业官网与响应式设计优化
如何快速搭建支持数据库操作的智能建站平台?
如何制作算命网站,怎么注册算命网站?
家庭服务器如何搭建个人网站?
ppt在线制作免费网站推荐,有什么下载免费的ppt模板网站?
如何在Golang中引入测试模块_Golang测试包导入与使用实践
免费网站制作appp,免费制作app哪个平台好?
建站之星24小时客服电话如何获取?
行程制作网站有哪些,第三方机票电子行程单怎么开?
定制建站哪家更专业可靠?推荐榜单揭晓
Python如何创建带属性的XML节点
如何生成腾讯云建站专用兑换码?
建站10G流量真的够用吗?如何应对访问高峰?
建站之星手机一键生成:多端自适应+小程序开发快速建站指南
简单实现Android文件上传
建站之星2.7模板:企业网站建设与h5定制设计专题
GML (Geography Markup Language)是什么,它如何用XML来表示地理空间信息?
如何快速查询域名建站关键信息?
Swift开发中switch语句值绑定模式
制作网站软件推荐手机版,如何制作属于自己的手机网站app应用?
关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)
黑客如何利用漏洞与弱口令入侵网站服务器?
已有域名如何快速搭建专属网站?
单页制作网站有哪些,朋友给我发了一个单页网站,我应该怎么修改才能把他变成自己的呢,请求高手指点迷津?
网站海报制作教学视频教程,有什么免费的高清可商用图片网站,用于海报设计?
详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)
网站制作软件有哪些,制图软件有哪些?
昆明网站制作哪家好,昆明公租房申请网上登录入口?
网页设计网站制作软件,microsoft office哪个可以创建网页?
宁波免费建站如何选择可靠模板与平台?
大连企业网站制作公司,大连2025企业社保缴费网上缴费流程?
*请认真填写需求信息,我们会在24小时内与您取得联系。