调用系统照相机和相册

本文通过实例演示如何在Android应用中调用系统相机和相册进行图片选择。首先介绍了一个显示头像的ImageView,并展示了点击后弹出的选项框实现。然后详细解释了项目的文件结构,包括AdvancedFileUtils(高级文件处理工具)和ImageUtils(图片处理工具类)。
摘要由CSDN通过智能技术生成

介绍的文章很多,这里通过一个实例来展示,先看看选项:一个显示头像的ImageView和点击后弹出的选项框(选项框的制作在之前的文章有介绍http://blog.csdn.net/nzzl54/article/details/52086007)


接下来是看看结构:


一个一个文件讲解:

1.AdvancedFileUtils:高级的文件处理工具

public class AdvancedFileUtils {
	public static File getDiskCacheDir(Context context, String uniqueName) {
		// Check if media is mounted or storage is built-in, if so, try and use
		// external cache dir
		// otherwise use internal cache dir

		final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()) || !isExternalStorageRemovable() ? getExternalCacheDir(
				context).getPath()
				: context.getCacheDir().getPath();

		return new File(cachePath + File.separator + uniqueName);
	}
	/**
	 * Check if external storage is built-in or removable.
	 *
	 * @return True if external storage is removable (like an SD card), false
	 *         otherwise.
	 */
	@TargetApi(9)
	public static boolean isExternalStorageRemovable() {
		if (Build.VERSION.SDK_INT >= 9) {
			return Environment.isExternalStorageRemovable();
		}
		return true;
	}

	/**
	 * Get the external app cache directory.
	 *
	 * @param context
	 *            The context to use
	 * @return The external cache dir
	 */
	private static File getExternalCacheDir(Context context) {
		// if (BaseVersionUtils.hasFroyo()) {
		// return context.getExternalCacheDir();
		// }

		// Before Froyo we need to construct the external cache dir ourselves
		final String cacheDir = "/Android/data/" + context.getPackageName()
				+ "/cache/";


		return new File(Environment.getExternalStorageDirectory().getPath()
				+ cacheDir);
	}
	/**
	 * 获取文件扩展名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileFormat(String fileName) {
		if (StringUtils.isEmpty(fileName))
			return "";

		int point = fileName.lastIndexOf('.');
		return fileName.substring(point + 1);
	}

	/**
	 * 根据文件绝对路径获取文件名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileName(String filePath) {
		if (StringUtils.isEmpty(filePath))
			return "";
		return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
	}
	/**
	 * 
	 * @param path 文件路径
	 * @param fileName 文件名,如xxx.jpg
	 * @param b
	 * @return 返回保存本地成功与否
	 */
	public static boolean saveBitmapToLocal(String path,String fileName,Bitmap b){
		if (b == null) {
			return false;
		}
		
		boolean result = false ;
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			FileOutputStream fos=null;
			
			try {
				fos = new FileOutputStream(path + fileName);
				b.compress(CompressFormat.JPEG, 100, fos);
				fos.flush();
				result = true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
								
		}	
		return result;
	}

}

2.BottomSelectorPopDialog:自定义弹框,略


3.Helper_Image:这里暂时不用,略


4.ImageUtils:工具类-图片处理

public class ImageUtils {
    public final static String SDCARD_MNT = "/mnt/sdcard";
    //	public final static String SDCARD = "/sdcard";
    public final static String SDCARD = Environment.getExternalStorageDirectory().getPath();
    // 请求相册
    public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
    //请求相机
    public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
    //请求裁剪
    public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;

    /**
     * 写图片文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下
     *
     * @throws IOException
     */
    public static void saveImage(Context context, String fileName, Bitmap bitmap)
            throws IOException {
        saveImage(context, fileName, bitmap, 100);
    }

    public static void saveImage(Context context, String fileName,
                                 Bitmap bitmap, int quality) throws IOException {
        if (bitmap == null || fileName == null || context == null)
            return;

        FileOutputStream fos = context.openFileOutput(fileName,
                Context.MODE_PRIVATE);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
        byte[] bytes = stream.toByteArray();
        fos.write(bytes);
        fos.close();
    }

    /**
     * 写图片文件到SD卡
     *
     * @throws IOException
     */
    public static void saveImageToSD(Context ctx, String filePath,
                                     Bitmap bitmap, int quality) throws IOException {
        if (bitmap != null) {
            File file = new File(filePath.substring(0,
                    filePath.lastIndexOf(File.separator)));
            if (!file.exists()) {
                file.mkdirs();
            }
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(filePath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
            if(ctx!=null){
                scanPhoto(ctx, filePath);
            }
        }
    }

    public static void saveBackgroundImage(Context ctx, String filePath, Bitmap bitmap, int quality) throws IOException{
        if (bitmap != null) {
            File file = new File(filePath.substring(0,
                    filePath.lastIndexOf(File.separator)));
            if (!file.exists()) {
                file.mkdirs();
            }
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(filePath));
            bitmap.compress(Bitmap.CompressFormat.PNG, quality, bos);
            bos.flush();
            bos.close();
            if(ctx!=null){
                scanPhoto(ctx, filePath);
            }
        }
    }


    /**
     * 让Gallery上能马上看到该图片
     */
    private static void scanPhoto(Context ctx, String imgFileName) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file = new File(imgFileName);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        ctx.sendBroadcast(mediaScanIntent);
    }

    /**
     * 获取bitmap
     *
     * @param context
     * @param fileName
     * @return
     */
    public static Bitmap getBitmap(Context context, String fileName) {
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = context.openFileInput(fileName);
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } finally {
 
手机端web页面调用相机相册以及文件上传的需求可以通过在webview中使用相应的API来实现。根据引用\[1\]中的描述,可以通过在webview端调用本地相机拍照或选择本地文件,并将文件地址传递给webview端进行显示。具体的实现可以参考引用\[2\]中提供的代码,该代码经过测试有效。至于将图片上传到服务器的问题,一般情况下可以由web端负责处理上传操作,如果需要在原生端进行上传,可以使用普通的文件上传方式。需要注意的是,在移动端上传时,默认情况下可能会打开系统照相机,这可能会导致用户体验不佳。根据引用\[3\]中的描述,可以通过修改相应的代码来解决这个问题。具体的修改方法可以参考引用\[3\]中提供的注释。 #### 引用[.reference_title] - *1* *2* [Android——UI篇:WebView里调用相机/文件选取照片并上传。](https://blog.csdn.net/qq_35373333/article/details/79565629)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [如何修改WebUpload上传文件默认调用系统相机,而不是手机相册?](https://blog.csdn.net/a910629820/article/details/79122624)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值