xml布局




AndroidManifest.xml中:权限




MainActivity中:

oncreat:

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.photo).setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewview){

toPhoto();
}
});


findViewById(R.id.camear).setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewview){

toCamera();
}
});


}

和oncreat同级的方法:

publicvoidpostFile(Filefile){



//sdcard/dliao/aaa.jpg
Stringpath=file.getAbsolutePath();

String[]split=path.split("\\/");


MediaTypeMEDIA_TYPE_PNG=MediaType.parse("image/png");


OkHttpClientclient=newOkHttpClient();

RequestBodyrequestBody=newMultipartBody.Builder()
.setType(MultipartBody.FORM)
//file
.addFormDataPart("imageFileName",split[split.length-1])
.addFormDataPart("image",split[split.length-1],RequestBody.create(MEDIA_TYPE_PNG,file))
.build();



Requestrequest=newRequest.Builder().post(requestBody).url("http://qhb.2dyt.com/Bwei/upload").build();


client.newCall(request).enqueue(newCallback(){
@Override
publicvoidonFailure(Callcall,IOExceptione){

}

@Override
publicvoidonResponse(Callcall,Responseresponse)throwsIOException{


System.out.println("response="+response.body().string());

}
});



}

staticfinalintINTENTFORCAMERA=1;
staticfinalintINTENTFORPHOTO=2;


publicStringLocalPhotoName;
publicStringcreateLocalPhotoName(){
LocalPhotoName=System.currentTimeMillis()+"face.jpg";
returnLocalPhotoName;
}

publicvoidtoCamera(){
try{
IntentintentNow=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
Uriuri=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(Exceptione){
e.printStackTrace();
}
}




/**
*打开相册
*/
publicvoidtoPhoto(){
try{
createLocalPhotoName();
IntentgetAlbum=newIntent(Intent.ACTION_GET_CONTENT);
getAlbum.setType("image/*");
startActivityForResult(getAlbum,INTENTFORPHOTO);
}catch(Exceptione){
e.printStackTrace();
}
}
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);

switch(requestCode){
caseINTENTFORPHOTO:
//相册
try{
//必须这样处理,不然在4.4.2手机上会出问题
UrioriginalUri=data.getData();
Filef=null;
if(originalUri!=null){
f=newFile(SDCardUtils.photoCacheDir,LocalPhotoName);
String[]proj={MediaStore.Images.Media.DATA};
Cursoractualimagecursor=this.getContentResolver().query(originalUri,proj,null,null,null);
if(null==actualimagecursor){
if(originalUri.toString().startsWith("file:")){
Filefile=newFile(originalUri.toString().substring(7,originalUri.toString().length()));
if(!file.exists()){
//地址包含中文编码的地址做utf-8编码
originalUri=Uri.parse(URLDecoder.decode(originalUri.toString(),"UTF-8"));
file=newFile(originalUri.toString().substring(7,originalUri.toString().length()));
}
FileInputStreaminputStream=newFileInputStream(file);
FileOutputStreamoutputStream=newFileOutputStream(f);
copyStream(inputStream,outputStream);
}
}else{
//系统图库
intactual_image_column_index=actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
Stringimg_path=actualimagecursor.getString(actual_image_column_index);
if(img_path==null){
InputStreaminputStream=this.getContentResolver().openInputStream(originalUri);
FileOutputStreamoutputStream=newFileOutputStream(f);
copyStream(inputStream,outputStream);
}else{
Filefile=newFile(img_path);
FileInputStreaminputStream=newFileInputStream(file);
FileOutputStreamoutputStream=newFileOutputStream(f);
copyStream(inputStream,outputStream);
}
}
Bitmapbitmap=ImageResizeUtils.resizeImage(f.getAbsolutePath(),1080);
intwidth=bitmap.getWidth();
intheight=bitmap.getHeight();
FileOutputStreamfos=newFileOutputStream(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(Exceptione){
e.printStackTrace();

}


break;
caseINTENTFORCAMERA:
//相机
try{

//file就是拍照完得到的原始照片
Filefile=newFile(SDCardUtils.photoCacheDir,LocalPhotoName);
Bitmapbitmap=ImageResizeUtils.resizeImage(file.getAbsolutePath(),1080);
intwidth=bitmap.getWidth();
intheight=bitmap.getHeight();
FileOutputStreamfos=newFileOutputStream(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(Exceptione){
e.printStackTrace();
}



break;
}

}

publicstaticvoidcopyStream(InputStreaminputStream,OutputStreamoutStream)throwsException{
try{
byte[]buffer=newbyte[1024];
intlen=0;
while((len=inputStream.read(buffer))!=-1){
outStream.write(buffer,0,len);
}
outStream.flush();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(inputStream!=null){
inputStream.close();
}
if(outStream!=null){
outStream.close();
}
}

}

ImageResizeUtils中:

packagecom.bwei.czx.czx10;

importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Matrix;
importandroid.media.ExifInterface;

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;

importstaticandroid.graphics.BitmapFactory.decodeFile;

/**
*Createdbyczxon2017/9/27.
*/

publicclassImageResizeUtils{

/**
*照片路径
*压缩后宽度的尺寸
*@parampath
*@paramspecifiedWidth
*/
publicstaticBitmapresizeImage(Stringpath,intspecifiedWidth)throwsException{


Bitmapbitmap=null;
FileInputStreaminStream=null;
Filef=newFile(path);
System.out.println(path);
if(!f.exists()){
thrownewFileNotFoundException();
}
try{
inStream=newFileInputStream(f);
intdegree=readPictureDegree(path);
BitmapFactory.Optionsopt=newBitmapFactory.Options();
//照片不加载到内存只能读取照片边框信息
opt.inJustDecodeBounds=true;
//获取这个图片的宽和高
decodeFile(path,opt);//此时返回bm为空



intinSampleSize=1;
finalintwidth=opt.outWidth;
//width照片的原始宽度specifiedWidth需要压缩的宽度
//1000980
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(IOExceptione){
e.printStackTrace();
}finally{
inStream=null;
}
}

if(bitmap==null){
returnnull;
}
Matrixm=newMatrix();
if(degree!=0){
//给Matrix设置旋转的角度
m.setRotate(degree);
bitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),m,true);
}
floatscaleValue=(float)specifiedWidth/bitmap.getWidth();
//等比压缩
m.setScale(scaleValue,scaleValue);
bitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),m,true);
returnbitmap;
}catch(OutOfMemoryErrore){
e.printStackTrace();
returnnull;
}catch(Exceptione){
e.printStackTrace();
returnnull;
}


}


/**
*读取图片属性:旋转的角度
*
*@parampath源信息
*图片绝对路径
*@returndegree旋转的角度
*/
publicstaticintreadPictureDegree(Stringpath){
intdegree=0;
try{
ExifInterfaceexifInterface=newExifInterface(path);
intorientation=exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
switch(orientation){
caseExifInterface.ORIENTATION_ROTATE_90:
degree=90;
break;
caseExifInterface.ORIENTATION_ROTATE_180:
degree=180;
break;
caseExifInterface.ORIENTATION_ROTATE_270:
degree=270;
break;
}
}catch(IOExceptione){
e.printStackTrace();
}
returndegree;
}


publicstaticvoidcopyStream(InputStreaminputStream,OutputStreamoutStream)throwsException{
try{
byte[]buffer=newbyte[1024];
intlen=0;
while((len=inputStream.read(buffer))!=-1){
outStream.write(buffer,0,len);
}
outStream.flush();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(inputStream!=null){
inputStream.close();
}
if(outStream!=null){
outStream.close();
}
}

}
}

SDcardutils中:

packagecom.bwei.czx.czx10;

importandroid.os.Environment;
importandroid.os.StatFs;

importjava.io.File;
importjava.io.IOException;

/**
*Createdbyczxon2017/9/27.
*/

publicclassSDCardUtils{
publicstaticfinalStringDLIAO="dliao";

publicstaticFilephotoCacheDir=SDCardUtils.createCacheDir(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+DLIAO);
publicstaticStringcacheFileName="myphototemp.jpg";



publicstaticbooleanisSDCardExist(){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
returntrue;
}else{
returnfalse;
}
}

publicstaticvoiddelFolder(StringfolderPath){
try{
delAllFile(folderPath);
StringfilePath=folderPath;
filePath=filePath.toString();
FilemyFilePath=newFile(filePath);
myFilePath.delete();
}catch(Exceptione){
e.printStackTrace();
}
}

publicstaticbooleandelAllFile(Stringpath){
booleanflag=false;
Filefile=newFile(path);
if(!file.exists()){
returnflag;
}
if(!file.isDirectory()){
returnflag;
}
String[]tempList=file.list();
Filetemp=null;
for(inti=0;i

这样就可以上传图片到网络了!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。

热门推荐

免责声明:网站资源来源于网络,如有侵权,请及时联系删除。

Copyright © 2024 好资源导航网. All Rights Reserved.

蜀ICP备2021004611号-4 网站地图