1、实现原理:用户打开相册或相机选择相片后,相片经过压缩并设置在控件上,在本地sd卡存一份(如果有的话,没有则内部存储,所以还
需要判断用户是否挂载了sd卡),然后在服务器上存储一份该,当下次再次启动应用时,会默认去sd卡加载该,如果本地没有,再会去联网请求
2、使用了picasso框架以及自定义BitmapUtils工具类
3、记得加上相关权限
<uses-permission android:name="androidpermissionINTERNET"></uses-permission>
<uses-permission android:name="androidpermissionCAMERA"/>
<uses-permission android:name="androidpermissionWRITE_EXTERNAL_STORAGE"></uses-permission>
/
public class MainActivity extends AppCompatActivity implements ViewOnClickListener {
private ImageView iv;//要设置的头像
private Button btn_photo;//调用相册按钮
private Button btn_camera;//调用相机按钮
@Override
protected void onCreate(Bundle savedInstanceState) {
superonCreate(savedInstanceState);
setContentView(Rlayoutactivity_main);
iv=(ImageView) findViewById(Ridiv);
btn_photo = (Button) findViewById(Ridbtn_photo);
btn_camera = (Button) findViewById(Ridbtn_camera);
btn_photosetOnClickListener(this);
btn_camerasetOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (vgetId()) {
case Ridbtn_photo://打开系统相册
Intent intent=new Intent(IntentACTION_PICK, MediaStoreImagesMediaEXTERNAL_CONTENT_URI);
startActivityForResult(intent,100);
break;
case Ridbtn_camera://打开系统相机
Intent intent2=new Intent(MediaStoreACTION_IMAGE_CAPTURE);
startActivityForResult(intent2,200);
break;
}
}
@RequiresApi(api = BuildVERSION_CODESKITKAT)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
superonActivityResult(requestCode, resultCode, data);
if(requestCode==100&&resultCode==RESULT_OK&&data!=null){//系统相册
Uri imageData = datagetData();
String path=getPath(imageData);
Bitmap bitmap = BitmapFactorydecodeFile(path);
Bitmap bitmap1 = BitmapUtilszoom(bitmap, ivgetWidth(), ivgetHeight());
Bitmap bitmap2 = BitmapUtilscircleBitmap(bitmap1);
//加载显示
ivsetImageBitmap(bitmap2);
//bitmap上传到服务器
//bitmap保存到本地
saveImage(bitmap2);
}else if(requestCode==200&&resultCode==RESULT_OK&&data!=null){//系统相机
Bitmap bitmap = (Bitmap) datagetExtras()get("data");
BitmapUtilszoom(bitmap,ivgetWidth(),ivgetHeight());
bitmap=BitmapUtilscircleBitmap(bitmap);
//加载显示
ivsetImageBitmap(bitmap);
//bitmap上传到服务器
//bitmap保存到本地
saveImage(bitmap);
}
}
/
数据的存储。(5种)
Bimap:内存层面的对象。
存储--->内存:
BitmapFactorydecodeFile(String filePath);
BitmapFactorydecodeStream(InputStream is);
内存--->存储:
bitmapcompress(BitmapCompressFormatPNG,100,OutputStream os);
/
private void saveImage(Bitmap bitmap) {
File filesDir;
if(EnvironmentgetExternalStorageState()equals(EnvironmentMEDIA_MOUNTED)){//判断sd卡是否挂载
//路径1:storage/sdcard/Android/data/包名/files
filesDir = thisgetExternalFilesDir("");
}else{//手机内部存储
//路径:data/data/包名/files
filesDir = thisgetFilesDir();
}
FileOutputStream fos = null;
try {
File file = new File(filesDir,"iconpng");
fos = new FileOutputStream(file);
bitmapcompress(BitmapCompressFormatPNG, 100,fos);
} catch (FileNotFoundException e) {
eprintStackTrace();
}finally{
if(fos != null){
try {
fosclose();
} catch (IOException e) {
eprintStackTrace();
}
}
}
}
//如果本地有,就不需要再去联网去请求
private boolean readImage() {
File filesDir;
if(EnvironmentgetExternalStorageState()equals(EnvironmentMEDIA_MOUNTED)){//判断sd卡是否挂载
//路径1:storage/sdcard/Android/data/包名/files
filesDir = getExternalFilesDir("");
}else{//手机内部存储
//路径:data/data/包名/files
filesDir = getFilesDir();
}
File file = new File(filesDir,"iconpng");
if(fileexists()){
//存储--->内存
Bitmap bitmap = BitmapFactorydecodeFile(filegetAbsolutePath());
ivsetImageBitmap(bitmap);
return true;
}
return false;
}
@RequiresApi(api = BuildVERSION_CODESKITKAT)
private String getPath(Uri uri) {
int sdkVersion = BuildVERSIONSDK_INT;
//高于442的版本
if (sdkVersion >= 19) {
Loge("TAG", "uri auth: " + urigetAuthority());
if (isExternalStorageDocument(uri)) {
String docId = DocumentsContractgetDocumentId(uri);
String[] split = docIdsplit(":");
String type = split[0];
if ("primary"equalsIgnoreCase(type)) {
return EnvironmentgetExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContractgetDocumentId(uri);
final Uri contentUri = ContentUriswithAppendedId(Uriparse("content://downloads/public_downloads"),
LongvalueOf(id));
return getDataColumn(this, contentUri, null, null);
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContractgetDocumentId(uri);
final String[] split = docIdsplit(":");
final String type = split[0];
Uri contentUri = null;
if ("image"equals(type)) {
contentUri = MediaStoreImagesMediaEXTERNAL_CONTENT_URI;
} else if ("video"equals(type)) {
contentUri = MediaStoreVideoMediaEXTERNAL_CONTENT_URI;
} else if ("audio"equals(type)) {
contentUri = MediaStoreAudioMediaEXTERNAL_CONTENT_URI;
}
final String selection = "_id=";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(this, contentUri, selection, selectionArgs);
} else if (isMedia(uri)) {
String[] proj = {MediaStoreImagesMediaDATA};
Cursor actualimagecursor = thismanagedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursorgetColumnIndexOrThrow(MediaStoreImagesMediaDATA);
actualimagecursormoveToFirst();
return actualimagecursorgetString(actual_image_column_index);
}
} else if ("content"equalsIgnoreCase(urigetScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return urigetLastPathSegment();
return getDataColumn(this, uri, null, null);
}
// File
else if ("file"equalsIgnoreCase(urigetScheme())) {
return urigetPath();
}
return null;
}
/
uri路径查询字段
@param context
@param uri
@param selection
@param selectionArgs
@return
/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = contextgetContentResolver()query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursormoveToFirst()) {
final int index = cursorgetColumnIndexOrThrow(column);
return cursorgetString(index);
}
} finally {
if (cursor != null)
cursorclose();
}
return null;
}
private boolean isExternalStorageDocument(Uri uri) {
return "comandroidexternalstoragedocuments"equals(urigetAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "comandroidprovidersdownloadsdocuments"equals(urigetAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "comandroidprovidersmediadocuments"equals(urigetAuthority());
}
public static boolean isMedia(Uri uri) {
return "media"equals(urigetAuthority());
}
/
@param uri The Uri to check
@return Whether the Uri authority is Google Photos
/
public static boolean isGooglePhotosUri(Uri uri) {
return "comgoogleandroidappsphotoscontent"equals(urigetAuthority());
}
/
判断本地是否有该,没有则去联网请求
/
@Override
protected void onResume() {
superonResume();
if(readImage()){
return;
}
}
}
//BitmapUtils工具类public class BitmapUtils { /
该方法用于将进行圆形处理
/ public static Bitmap circleBitmap(Bitmap source){ //默认只对宽进行处理 int width=sourcegetWidth(); Bitmap bitmap=BitmapcreateBitmap(width,width,BitmapConfigARGB_8888); Canvas canvas=new Canvas(bitmap); Paint paint=new Paint(); //设置抗锯齿 paintsetAntiAlias(true); canvasdrawCircle(width/2,width/2,width/2,paint); paintsetXfermode(new PorterDuffXfermode(PorterDuffModeSRC_IN)); canvasdrawBitmap(source,0,0,paint); return bitmap; } / 该方法用于压缩处理,注意width、height参数的类型必须是float / public static Bitmap zoom(Bitmap source,float width,float height){ Matrix matrix=new Matrix(); //进行压缩处理 matrixpostScale(width/sourcegetWidth(),height/sourcegetHeight()); Bitmap bitmap = BitmapcreateBitmap(source, 0, 0, sourcegetWidth(), sourcegetHeight(), matrix, false); return bitmap; }}
以上所述是小编给大家介绍的Android实现调用系统图库与相机设置头像并保存在本地及服务器 ,希望对大家有所帮助
实现将该Bitmap图像保存在本地磁盘的 *** 作步骤如下:
1、在Bitmap中编辑代码。首先编辑头代码:
public static void saveBitmap(Bitmap bitmap,int path)。
2、接着编辑条件代码:
{
String savePath;
File filePic;
if (EnvironmentgetExternalStorageState()equals(
EnvironmentMEDIA_MOUNTED)) {
savePath = path;
} else {
Logd("xxx", "saveBitmap: 1return");
return;
}
3、最后编辑主代码:
try {
filePic = new File(savePath + "jpg");
if (!filePicexists()) {
filePicgetParentFile()mkdirs();
filePiccreateNewFile();
}
FileOutputStream fos = new FileOutputStream(filePic);
bitmapcompress(BitmapCompressFormatJPEG, 100, fos);
fosflush();
fosclose();
} catch (IOException e) {
eprintStackTrace();
Logd("xxx", "saveBitmap: 2return");
return;
}
Logd("xxx", "saveBitmap: " + filePicgetAbsolutePath());
}
1、控制大小和位置
/
获取对话框的窗口对象及参数对象以修改对话框的布局设置,
可以直接调用getWindow(),表示获得这个Activity的Window
对象,这样这可以以同样的方式改变这个Activity的属性
/
Window dialogWindow = dialoggetWindow();
WindowManagerLayoutParams lp = dialogWindowgetAttributes();
dialogWindowsetGravity(GravityLEFT | GravityTOP);
/
lpx与lpy表示相对于原始位置的偏移
当参数值包含GravityLEFT时,对话框出现在左边,所以lpx就表示相对左边的偏移,负值忽略
当参数值包含GravityRIGHT时,对话框出现在右边,所以lpx就表示相对右边的偏移,负值忽略
当参数值包含GravityTOP时,对话框出现在上边,所以lpy就表示相对上边的偏移,负值忽略
当参数值包含GravityBOTTOM时,对话框出现在下边,所以lpy就表示相对下边的偏移,负值忽略
当参数值包含GravityCENTER_HORIZONTAL时
,对话框水平居中,所以lpx就表示在水平居中的位置移动lpx像素,正值向右移动,负值向左移动
当参数值包含GravityCENTER_VERTICAL时
,对话框垂直居中,所以lpy就表示在垂直居中的位置移动lpy像素,正值向右移动,负值向左移动
gravity的默认值为GravityCENTER,即GravityCENTER_HORIZONTAL |
GravityCENTER_VERTICAL
本来setGravity的参数值为GravityLEFT | GravityTOP时对话框应出现在程序的左上角,但在
我手机上测试时发现距左边与上边都有一小段距离,而且垂直坐标把程序标题栏也计算在内了,
GravityLEFT, GravityTOP, GravityBOTTOM与GravityRIGHT都是如此,据边界有一小段距离
/
lpx = 100; // 新位置X坐标
lpy = 100; // 新位置Y坐标
lpwidth = 300; // 宽度
lpheight = 300; // 高度
lpalpha = 07f; // 透明度
// 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
// dialogonWindowAttributesChanged(lp);
dialogWindowsetAttributes(lp);
/
将对话框的大小按屏幕大小的百分比设置
/
// WindowManager m = getWindowManager();
// Display d = mgetDefaultDisplay(); // 获取屏幕宽、高用
// WindowManagerLayoutParams p = getWindow()getAttributes(); // 获取对话框当前的参数值
// pheight = (int) (dgetHeight() 06); // 高度设置为屏幕的06
// pwidth = (int) (dgetWidth() 065); // 宽度设置为屏幕的095
// dialogWindowsetAttributes(p);
以上就是关于安卓从手机相册获取照片作为头像缓存地址全部的内容,包括:安卓从手机相册获取照片作为头像缓存地址、C#中图片已经保存于Bitmap中,如何实现将该Bitmap图像保存在本地磁盘、android怎么获取图片的大小等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)