您的位置:首页 > 移动开发 > Android开发

Android实现选择相册图片和拍照,并手动截图返回图片路径和Bitmap对象

2016-08-17 20:52 681 查看
直接贴代码: 不懂的地方可以联系我扣扣 1668126018

以下是几个类: 代码Copy可以直接用 记得加读写权限

package com.mcdemo.icon;

import android.app.Activity;

import android.widget.TextView;

/**

* @author meteorshower

* Add Title and Message

*/

public abstract class BaseContentPopup extends BasePopup {

protected TextView tvTitle,tvMessage;

public BaseContentPopup(Activity context) {
super(context);
findTitleByID();
findMessageByID();
}

public BaseContentPopup(Activity context, int width, int height){
super(context, width, height);
findTitleByID();
findMessageByID();
}

public abstract void findTitleByID();
public abstract void findMessageByID();

public void setTitle(int resources){
tvTitle.setText(resources);
}

public void setTitle(String value){
tvTitle.setText(value);
}

protected void setTitleColor(int color){
tvTitle.setTextColor(getContext().getResources().getColor(color));
}

public void setMessage(int resources){
tvMessage.setText(resources);
}

public void setMessage(String value){
tvMessage.setText(value);
}

/** 文本显示样式 居中,左右对齐 */
public void setMessageGravity(int gravity){
tvMessage.setGravity(gravity);
}

public void setMessageColor(int color){
tvMessage.setTextColor(getContext().getResources().getColor(color));
}


}

package com.mcdemo.icon;

import android.app.Activity;

import android.widget.Button;

/**

* @author meteorshower

* A Click Event

*/

public abstract class BaseEventPopup extends BaseContentPopup {

protected Button btnEvent,btnShare;
protected onEventClickListener eventListener;

public BaseEventPopup(Activity context) {
super(context);
findEventByID();
}

public BaseEventPopup(Activity context, int width, int height){
super(context, width, height);
findEventByID();
}

public abstract void findEventByID();

public void setEventText(int resources){
btnEvent.setText(resources);
}

public void setEventText(String value){
btnEvent.setText(value);
}

public void setEventColor(int color){
btnEvent.setTextColor(getContext().getResources().getColor(color));
}

public void setOnEventClickListener(onEventClickListener listener){
this.eventListener = listener;
}

public interface onEventClickListener{
public void onEventClick(PopupObject obj);
}


}

package com.mcdemo.icon;

import android.app.Activity;

import android.graphics.drawable.BitmapDrawable;

import android.view.Gravity;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.WindowManager;

import android.view.animation.Animation;

import android.view.animation.ScaleAnimation;

import android.view.animation.TranslateAnimation;

import android.widget.PopupWindow;

import android.widget.PopupWindow.OnDismissListener;

import android.widget.RelativeLayout.LayoutParams;

import android.widget.TextView;

public abstract class BasePopup implements PopupPage {

protected View popupView;
protected PopupWindow mPopupWindow;
private Activity context;

public BasePopup(Activity context) {
this(context, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}

public BasePopup(Activity context, int width, int height) {

this.context = context;

popupView = setContentView(LayoutInflater.from(context));
popupView.setFocusableInTouchMode(true);

mPopupWindow = new PopupWindow(popupView, width, height);

mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
mPopupWindow.setFocusable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setAnimationStyle(0);
}

public abstract Animation loadAnim();

public abstract View getStartAnimViewGroup();

@Override
public View getView() {
return popupView;
}

public Activity getContext() {
return context;
}

public void showPopupWindow() {
showPopupWindow(R.id.AppWidget);
}

public void showPopupWindow(int resource) {
try {
Activity context = getContext();
mPopupWindow.showAtLocation(context.findViewById(resource), Gravity.CENTER
| Gravity.CENTER_HORIZONTAL, 0, 0);

if (loadAnim() != null && getStartAnimViewGroup() != null) {
getStartAnimViewGroup().startAnimation(loadAnim());
}
} catch (Exception e) {
}
}

public void showPopupWindow(View view) {
try {
mPopupWindow.showAsDropDown(view);
if (loadAnim() != null && getStartAnimViewGroup() != null) {
getStartAnimViewGroup().startAnimation(loadAnim());
}
} catch (Exception e) {
}
}

public void showPopupWindos(View v, int gravity, int x, int y) {
try {
mPopupWindow.showAtLocation(v, gravity, x, y);
if (loadAnim() != null && getStartAnimViewGroup() != null) {
getStartAnimViewGroup().startAnimation(loadAnim());
}
} catch (Exception e) {
}
}

/**
* 设置弹框大小
*/
public void setPopupLayoutParams(int width, int height) {
mPopupWindow = new PopupWindow(popupView, width, height);
}

/**
* Popup是否显示状态
*/
public boolean isShowPopup() {
if (mPopupWindow.isShowing()) {
return true;
}
return false;
}

/**
* 关闭Popup
*/
public void dismiss() {
try {
mPopupWindow.dismiss();
} catch (Exception e) {
}
}

/**
* 设置输入法弹出 上移布局,不影响操作使用
*/
public void inputMethodUpload() {
mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}

/**
* 屏蔽back键
*/
public void shieldBack() {
mPopupWindow.setBackgroundDrawable(null);
}

/**
* popup Dismiss接口监听
*/
public void setOnDismissPopupListener(final OnDismissPoppupListener listener) {
if (listener != null) {
mPopupWindow.setOnDismissListener(new OnDismissListener() {

@Override
public void onDismiss() {
listener.onDismissPopup();
}
});
}
}

public interface OnDismissPoppupListener {

public void onDismissPopup();
}

/**
* 设置点击事件关闭Popup
*/
protected void setCancelPopupListener(View view) {
view.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
dismiss();
}
});
}

protected Animation getTranslateAnimation(int durationMillis, int start) {
return getTranslateAnimation(start, 0, durationMillis);
}

/**
* 生成TranslateAnimation
*
* @param durationMillis 动画显示时间
* @param start          初始位置
* @return
*/
protected Animation getTranslateAnimation(int start, int end, int durationMillis) {
Animation translateAnimation = new TranslateAnimation(0, 0, start, end);
translateAnimation.setDuration(durationMillis);
translateAnimation.setFillEnabled(true);
translateAnimation.setFillAfter(true);
translateAnimation.setFillBefore(true);
return translateAnimation;
}

/**
* 生成ScaleAnimation
*
* @return
*/
protected Animation getScaleAnimation() {
Animation scaleAnimation = new ScaleAnimation(0.7f, 1f, 0.7f, 1f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(200);
scaleAnimation.setFillEnabled(true);
scaleAnimation.setFillAfter(true);
scaleAnimation.setFillBefore(true);
return scaleAnimation;
}

/**
* 返回String值
*/
public String getResourcesStr(int strResources) {
return context.getResources().getString(strResources);
}

/**
* 返回Color值
*/
public int getResourcesColor(int colorResources) {
return context.getResources().getColor(colorResources);
}

/**
* 获取控件的文字内容(仅限于TextView及其子类)
*/
public String getViewStr(TextView textView) {
return textView.getText().toString().trim();
}


}

package com.mcdemo.icon;

import java.io.File;

import android.app.Activity;

import android.os.Environment;

public class FileUtils {

// SD卡路径
public static String getSDPath(Activity Activity) {
String DataPath;
if (CheckSDExist() == true)
DataPath = Environment.getExternalStorageDirectory().toString();
else
DataPath = Activity.getFilesDir().getPath();

return DataPath;
}

// 获得应用文件夹路径
public static String getRootPath(Activity Activity) {
return FileUtils.getSDPath(Activity) + File.separator + "Thindo"
+ File.separator;
}

public static String getUploadCache(Activity Activity) {
return getRootPath(Activity) + "upload_cache";
}

/**
* 图片缓存地路径
*/
public static String getImageCachePath(Activity Activity) {
return getRootPath(Activity) + "ImageLoader" + File.separator;
}

/**
* 崩溃日志缓存路径
*/
public static String getLogPath(Activity Activity) {
return getRootPath(Activity) + "log" + File.separator;
}

// 建立应用程序的相关路径
public static void BuildAppPath(Activity Activity) {
FileUtils.mkdir(getImageCachePath(Activity));
}

public static boolean isExist(String path) {
if (path == null)
return false;
File file = new File(path);
return file.exists();
}

public static boolean mkdir(String path) {
File file = new File(path);
if (file.exists() == false)
return file.mkdirs();
return true;
}

public static boolean CheckSDExist() {
boolean sdCardExist = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
return sdCardExist;
}

/**
* 递删除文件和文件夹
*
* @param file 要删除的根目录
*/
public static void deleteFile(File file) {
if (file.exists() == false) {
return;
} else {
if (file.isFile()) {
file.delete();
return;
}
if (file.isDirectory()) {
File[] childFile = file.listFiles();
if (childFile == null || childFile.length == 0) {
file.delete();
return;
}
for (File f : childFile) {
deleteFile(f);
}
file.delete();
}
}
}


}

package com.mcdemo.icon;

import android.app.Activity;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.net.Uri;

import android.os.Environment;

import android.view.View;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

public class ImageCacheUitl {

private static ImageCacheUitl self;

private ImageCacheUitl() {
}

public static ImageCacheUitl getInstetn() {
if (self == null) {
self = new ImageCacheUitl();
}
return self;
}

// 保存图片到手机缓存 没使用
public Boolean savaImage(String path, Bitmap bitmap) {
Boolean returnObj = false;
FileOutputStream fileOutputStream = null;
File file = null;
try {
file = new File(getSDCarPath() + path);
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
} catch (Exception e) {
e.printStackTrace();
}
if (fileOutputStream != null) {
bitmap.compress(Bitmap.CompressFormat.PNG, 30, fileOutputStream);
try {
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
returnObj = true;
}
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return returnObj;
}

public String getSDCarPath() {
String root = "";
File sdCardDir = null;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
sdCardDir = Environment.getExternalStorageDirectory();// 获取SDCard目
root = sdCardDir.toString() + "/fmb/";
}

return root;
}

/**
* 按照比例大小压缩
*
* @param srcPath
* @return
*/
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空

newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 1200f;//这里设置高度为800f
float ww = 800f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap, srcPath);//压缩好比例大小后再进行质量压缩
}

/**
* 质量压缩
*
* @param image
* @return
*/
public static Bitmap compressImage(Bitmap image, String srcPath) {
savaImagePath(image, srcPath);
return image;
}

private static void savaImagePath(Bitmap bitmap, String path) {

File file = new File(path);
try {
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 加载本地图片
*
* @param url
* @return
*/

public static Bitmap getLoacalBitmap(String url) {
try {
FileInputStream fis = new FileInputStream(url);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}

public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // 用数据装
int len = -1;
while ((len = is.read(buffer)) != -1) {
outstream.write(buffer, 0, len);
}
outstream.close();

// 关闭流一定要记得。
return outstream.toByteArray();
}

//对view截图并保存到相册
public static Bitmap screenShot(View view, String fileName,Activity Activity) throws Exception {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
//上面2行必须加入,如果不加如view.getDrawingCache()返回null
Bitmap bitmap = view.getDrawingCache();

File appDir = new File(FileUtils.getSDPath(Activity), "Thindo");
String Name = fileName + ".jpg";
File file = new File(appDir, Name);

if (!appDir.exists()) {
appDir.mkdir();
}

try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
scanPhoto(file.getPath(),Activity);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;

}

private static void scanPhoto(String imgFileName, Activity Activity) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(imgFileName);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Activity.sendBroadcast(mediaScanIntent);

}


}

package com.mcdemo.icon;

import java.util.ArrayList;

public class PopupObject {

private int what;
private String value;
private ArrayList<Object> arrayList = new ArrayList<Object>();
private Object object;

public int getWhat() {
return what;
}

public void setWhat(int what) {
this.what = what;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public ArrayList<Object> getArrayList() {
return arrayList;
}

public void setArrayList(ArrayList<Object> arrayList) {
this.arrayList = arrayList;
}

public Object getObject() {
return object;
}

public void setObject(Object object) {
this.object = object;
}


}

package com.mcdemo.icon;

import android.view.LayoutInflater;

import android.view.View;

public interface PopupPage {

public View getView();

public View setContentView(LayoutInflater inflater);


}

package com.mcdemo.icon;

import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.provider.MediaStore;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.animation.Animation;

import java.io.File;

/**

* 修改头像

*/

public class PopupPhotoView extends BaseEventPopup implements OnClickListener {

public static final String IMAGE_FILE_NAME = “tempImage.jpg”;

private final Activity context;

public PopupPhotoView(Activity context) {
super(context);
this.context = context;
}

@Override
public View setContentView(LayoutInflater inflater) {
return inflater.inflate(R.layout.popup_photo_view, null);
}

public void hiddlePoho() {
getView().findViewById(R.id.bt_photograph).setVisibility(View.GONE);
}

@Override
public void findEventByID() {
getView().findViewById(R.id.other_cancel).setOnClickListener(this);
getView().findViewById(R.id.bt_photoalbum).setOnClickListener(this);
getView().findViewById(R.id.bt_photograph).setOnClickListener(this);
getView().findViewById(R.id.app_widget).setOnClickListener(this);
}

@Override
public void findTitleByID() {

}

@Override
public void findMessageByID() {

}

@Override
public Animation loadAnim() {
return null;
}

@Override
public View getStartAnimViewGroup() {
return getView().findViewById(R.id.popup_parent_layout);
}

@Override
public void onClick(View v) {
dismiss();
switch (v.getId()) {
case R.id.bt_photograph://拍照
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Tools.hasSdcard()) {// 判断存储卡是否可以用,可用进行存储
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(FileUtils.getRootPath((Activity) context), IMAGE_FILE_NAME)));
}
getContext().startActivityForResult(intentFromCapture, 1);
break;
case R.id.bt_photoalbum://相册
Intent intentFromGallery = new Intent();
intentFromGallery.setType("image/*"); // 设置文件类型
intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
getContext().startActivityForResult(intentFromGallery, 0);
break;
default:
break;
}
}


}

package com.mcdemo.icon;

import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.os.Environment;

public class Tools {

public static void startActivity(Context context, Class<? extends Activity> cls) {
Intent intent = new Intent(context, cls);
context.startActivity(intent);
}

/**
* 检查是否存在SDCard
* @return
*/
public static boolean hasSdcard(){
String state = Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
return true;
}else{
return false;
}
}
private static long lastClickTime;

/** 防止按钮双击 */
public static boolean isFastDoubleClick() {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (0 < timeD && timeD < 500) {
lastClickTime = time;
return true;
}
lastClickTime = time;

return false;
}
/** 防止按钮双击 */
public static boolean isFastDoubleLongClick() {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (0 < timeD && timeD < 1000) {
lastClickTime = time;
return true;
}
lastClickTime = time;

return false;
}


}

MainActivity 调用:

package com.mcdemo.icon;

import android.content.Intent;

import android.graphics.Bitmap;

import android.net.Uri;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.ImageView;

import java.io.File;

public class MainActivity extends AppCompatActivity {

private ImageView iv;

private int imageType;
private PopupPhotoView popup;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageType = 1;
popup = new PopupPhotoView(MainActivity.this);
popup.showPopupWindow();
}
});

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
startPhotoZoom(data.getData());
break;
case 1:
if (Tools.hasSdcard()) {
File tempFile = new File(FileUtils.getRootPath(this) + PopupPhotoView
.IMAGE_FILE_NAME);
startPhotoZoom(Uri.fromFile(tempFile));
}
break;
case 2:
if (data == null)
return;

Bundle extras = data.getExtras();
if (extras == null)
return;
String iamgeName = "temp" + imageType + ".jpg";
Bitmap photo = extras.getParcelable("data");
ImageCacheUitl imageCacheUitl = ImageCacheUitl.getInstetn();
String path = imageCacheUitl.getSDCarPath() + iamgeName;

Boolean flg = imageCacheUitl.savaImage(iamgeName, photo);
iv.setImageBitmap(photo);

break;

}
}
}

/**
* 裁剪图片方法实现
*/
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");// 设置裁剪
intent.putExtra("aspectX", 1);// aspectX aspectY 是宽高的比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 320);// outputX outputY 是裁剪图片宽高
intent.putExtra("outputY", 320);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);
}


}

布局文件:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 图片 截图