24.Android 图片工具ImageUtil

24.Android 图片工具ImageUtil

  • Android 图片工具ImageUtil

    • 裁图
    • Bitmap圆角
    • 缩略图
    • 视频缩略图
    • 各种类型转换
    • ImageUtil全部源码

裁图

    /**
     * 调用系统自带裁图工具
     *
     * @param activity
     * @param size
     * @param uri
     * @param action
     * @param cropFile
     */
    public static void cropPicture(Activity activity, int size, Uri uri, int action, File cropFile) {
        try {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 返回格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("crop", true);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", size);
            intent.putExtra("outputY", size);
            intent.putExtra("scale", true);
            intent.putExtra("scaleUpIfNeeded", true);
            intent.putExtra("cropIfNeeded", true);
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropFile));
            activity.startActivityForResult(intent, action);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用系统自带裁图工具
     * outputX = 250
     * outputY = 250
     *
     * @param activity
     * @param uri
     * @param action
     * @param cropFile
     */
    public static void cropPicture(Activity activity, Uri uri, int action, File cropFile) {
        cropPicture(activity, 250, uri, action, cropFile);
    }

    /**
     * 调用系统自带裁图工具
     * 并保存文件
     * outputX = 250
     * outputY = 250
     *
     * @param activity
     * @param uri
     * @param action
     * @param appName
     * @param application
     * @return
     */
    public static File cropPicture(Activity activity, Uri uri, int action, String appName, Application application) {
        File resultFile = createImageFile(appName, application);
        cropPicture(activity, 250, uri, action, resultFile);
        return resultFile;
    }

    /**
     * 创建图片文件
     *
     * @param appName
     * @param application
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static File createImageFile(String appName, Application application) {
        File folder = createImageFileInCameraFolder(appName, application);
        String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis());
        return new File(folder, filename + ".jpg");
    }

    /**
     * 创建图片文件夹
     *
     * @param appName
     * @param application
     * @return
     */
    public static File createImageFileInCameraFolder(String appName, Application application) {
        String folder = ImageUtil.createAPPFolder(appName, application);
        File file = new File(folder, "image");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 创建App文件夹
     *
     * @param appName
     * @param application
     * @return
     */
    public static String createAPPFolder(String appName, Application application) {
        return createAPPFolder(appName, application, null);
    }

    /**
     * 创建App文件夹
     *
     * @param appName
     * @param application
     * @param folderName
     * @return
     */
    public static String createAPPFolder(String appName, Application application, String folderName) {
        File root = Environment.getExternalStorageDirectory();
        File folder;
        /**
         * 如果存在SD卡
         */
        if (DeviceUtil.isSDCardAvailable() && root != null) {
            folder = new File(root, appName);
            if (!folder.exists()) {
                folder.mkdirs();
            }
        } else {
            /**
             * 不存在SD卡,就放到缓存文件夹内
             */
            root = application.getCacheDir();
            folder = new File(root, appName);
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }
        if (folderName != null) {
            folder = new File(folder, folderName);
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }
        return folder.getAbsolutePath();
    }

Bitmap圆角

    /**
     * 获取圆角Bitmap
     *
     * @param srcBitmap
     * @param radius
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap srcBitmap, float radius) {
        Bitmap resultBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(resultBitmap);
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, srcBitmap.getWidth(), srcBitmap.getHeight());
        RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(0xBDBDBE);
        canvas.drawRoundRect(rectF, radius, radius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(srcBitmap, rect, rect, paint);
        return resultBitmap;
    }

缩略图

    /**
     * 获取缩略图
     *
     * @param path
     * @param targetWidth
     * @return
     */
    public static String getThumbnailImage(String path, int targetWidth) {
        Bitmap scaleImage = decodeScaleImage(path, targetWidth, targetWidth);
        try {
            File file = File.createTempFile("image", ".jpg");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            scaleImage.compress(Bitmap.CompressFormat.JPEG, 60, fileOutputStream);
            fileOutputStream.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return path;
        }
    }

    /**
     * 图片解析
     *
     * @param context
     * @param resId
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static Bitmap decodeScaleImage(Context context, int resId, int targetWidth, int targetHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resId, options);
        options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId, options);
        return bitmap;
    }

    /**
     * 计算样本大小
     *
     * @param options
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int targetWidth, int targetHeight) {
        int height = options.outHeight;
        int width = options.outWidth;
        int scale = 1;
        if (height > targetHeight || width > targetWidth) {
            int heightScale = Math.round((float) height / (float) targetHeight);
            int widthScale = Math.round((float) width / (float) targetWidth);
            scale = heightScale > widthScale ? heightScale : widthScale;
        }
        return scale;
    }

    /**
     * 获取BitmapFactory.Options
     *
     * @param pathName
     * @return
     */
    public static BitmapFactory.Options getBitmapOptions(String pathName) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, opts);
        return opts;
    }

    /**
     * 获取图片角度
     *
     * @param filename
     * @return
     */
    public static int readPictureDegree(String filename) {
        short degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(filename);
            int anInt = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
            switch (anInt) {
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                case ExifInterface.ORIENTATION_TRANSPOSE:
                case ExifInterface.ORIENTATION_TRANSVERSE:
                default:
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return degree;
    }

    /**
     * 旋转ImageView
     *
     * @param degree
     * @param source
     * @return
     */
    public static Bitmap rotatingImageView(int degree, Bitmap source) {
        Matrix matrix = new Matrix();
        matrix.postRotate((float) degree);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }

视频缩略图

    /**
     * 保存视频缩略图
     *
     * @param file
     * @param width
     * @param height
     * @param kind
     * @return
     */
    public static String saveVideoThumbnail(File file, int width, int height, int kind) {
        Bitmap videoThumbnail = getVideoThumbnail(file.getAbsolutePath(), width, height, kind);
        File thumbFile = new File(PathUtil.getInstance().getVideoPath(), "th" + file.getName());
        try {
            thumbFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(thumbFile);
        } catch (FileNotFoundException var10) {
            var10.printStackTrace();
        }
        videoThumbnail.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
        try {
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileOutputStream.close();
        } catch (IOException var8) {
            var8.printStackTrace();
        }
        return thumbFile.getAbsolutePath();
    }

各种类型转换

    /**
     * Image resource ID was converted into a byte [] data
     * 图片资源ID 转换 为 图片 byte[] 数据
     *
     * @param context
     * @param imageResourceId
     * @return
     */
    public static byte[] toByteArray(Context context, int imageResourceId) {
        Bitmap bitmap = ImageUtil.toBitmap(context, imageResourceId);
        if (bitmap != null) {
            return ImageUtil.toByteArray(bitmap);
        } else {
            return null;
        }
    }

    /**
     * ImageView getDrawable () into a byte [] data
     * ImageView的getDrawable() 转换为 byte[] 数据
     *
     * @param imageView
     * @return
     */
    public static byte[] toByteArray(ImageView imageView) {
        Bitmap bitmap = ImageUtil.toBitmap(imageView);
        if (bitmap != null)
            return ImageUtil.toByteArray(bitmap);
        else {
            Log.w(ImageUtil.TAG,
                    "the ImageView imageView content was invalid");
            return null;
        }
    }

    /**
     * byte [] data type conversion for Bitmap data types
     * byte[]数据类型转换为 Bitmap数据类型
     *
     * @param imageData
     * @return
     */
    public static Bitmap toBitmap(byte[] imageData) {
        if ((imageData != null) && (imageData.length != 0)) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                    imageData.length);
            return bitmap;
        } else {
            Log.w(ImageUtil.TAG, "the byte[] imageData content was invalid");
            return null;
        }
    }

    /**
     * Image resource ID is converted to Bitmap type data
     * 资源ID 转换为 Bitmap类型数据
     *
     * @param context
     * @param imageResourceId
     * @return
     */
    public static Bitmap toBitmap(Context context, int imageResourceId) {
        // 将图片转化为位图
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
                imageResourceId);
        if (bitmap != null) {
            return bitmap;
        } else {
            Log.w(ImageUtil.TAG,
                    "the int imageResourceId content was invalid");
            return null;
        }
    }

    /**
     * ImageView types into a Bitmap
     * ImageView类型转换为Bitmap
     *
     * @param imageView
     * @return
     */
    public static Bitmap toBitmap(ImageView imageView) {
        if (imageView.getDrawable() != null) {
            Bitmap bitmap = ImageUtil.toBitmap(imageView.getDrawable());
            return bitmap;
        } else {
            return null;
        }
    }

    /**
     * Bitmap type is converted into a image byte [] data
     * Bitmap类型 转换 为图片 byte[] 数据
     *
     * @param bitmap
     * @return
     */
    public static byte[] toByteArray(Bitmap bitmap) {
        if (bitmap != null) {
            int size = bitmap.getWidth() * bitmap.getHeight() * 4;
            // 创建一个字节数组输出流,流的大小为size
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
                    size);
            // 设置位图的压缩格式,质量为100%,并放入字节数组输出流中
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    byteArrayOutputStream);
            // 将字节数组输出流转化为字节数组byte[]
            byte[] imageData = byteArrayOutputStream.toByteArray();
            return imageData;
        } else {
            Log.w(ImageUtil.TAG,
                    "the Bitmap bitmap content was invalid");
            return null;
        }

    }

    /**
     * Drawable type into a Bitmap
     * Drawable 类型转换为 Bitmap类型
     *
     * @param drawable
     * @return
     */
    public static Bitmap toBitmap(Drawable drawable) {
        if (drawable != null) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            return bitmap;
        } else {
            Log.w(ImageUtil.TAG,
                    "the Drawable drawable content was invalid");
            return null;
        }
    }

    /**
     * Bitmap type into a Drawable
     * Bitmap 类型转换为 Drawable类型
     *
     * @param bitmap
     * @return
     */
    public static Drawable toDrawable(Bitmap bitmap) {
        if (bitmap != null) {
            Drawable drawable = new BitmapDrawable(bitmap);
            return drawable;
        } else {
            Log.w(ImageUtil.TAG,
                    "the Bitmap bitmap content was invalid");
            return null;
        }
    }

ImageUtil全部源码

public class ImageUtil {

    private static final String TAG = "ImageUtil";

    public static final int ACTION_SET_AVATAR = 260;
    public static final int ACTION_SET_COVER = 261;
    public static final int ACTION_TAKE_PIC = 262;
    public static final int ACTION_TAKE_PIC_FOR_GRIDVIEW = 263;
    public static final int ACTION_PICK_PIC = 264;
    public static final int ACTION_ACTION_CROP = 265;

    /**
     * 调用系统自带裁图工具
     *
     * @param activity
     * @param size
     * @param uri
     * @param action
     * @param cropFile
     */
    public static void cropPicture(Activity activity, int size, Uri uri, int action, File cropFile) {
        try {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 返回格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("crop", true);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", size);
            intent.putExtra("outputY", size);
            intent.putExtra("scale", true);
            intent.putExtra("scaleUpIfNeeded", true);
            intent.putExtra("cropIfNeeded", true);
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropFile));
            activity.startActivityForResult(intent, action);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用系统自带裁图工具
     * outputX = 250
     * outputY = 250
     *
     * @param activity
     * @param uri
     * @param action
     * @param cropFile
     */
    public static void cropPicture(Activity activity, Uri uri, int action, File cropFile) {
        cropPicture(activity, 250, uri, action, cropFile);
    }

    /**
     * 调用系统自带裁图工具
     * 并保存文件
     * outputX = 250
     * outputY = 250
     *
     * @param activity
     * @param uri
     * @param action
     * @param appName
     * @param application
     * @return
     */
    public static File cropPicture(Activity activity, Uri uri, int action, String appName, Application application) {
        File resultFile = createImageFile(appName, application);
        cropPicture(activity, 250, uri, action, resultFile);
        return resultFile;
    }

    /**
     * 创建图片文件
     *
     * @param appName
     * @param application
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static File createImageFile(String appName, Application application) {
        File folder = createImageFileInCameraFolder(appName, application);
        String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis());
        return new File(folder, filename + ".jpg");
    }

    /**
     * 创建图片文件夹
     *
     * @param appName
     * @param application
     * @return
     */
    public static File createImageFileInCameraFolder(String appName, Application application) {
        String folder = ImageUtil.createAPPFolder(appName, application);
        File file = new File(folder, "image");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 创建App文件夹
     *
     * @param appName
     * @param application
     * @return
     */
    public static String createAPPFolder(String appName, Application application) {
        return createAPPFolder(appName, application, null);
    }

    /**
     * 创建App文件夹
     *
     * @param appName
     * @param application
     * @param folderName
     * @return
     */
    public static String createAPPFolder(String appName, Application application, String folderName) {
        File root = Environment.getExternalStorageDirectory();
        File folder;
        /**
         * 如果存在SD卡
         */
        if (DeviceUtil.isSDCardAvailable() && root != null) {
            folder = new File(root, appName);
            if (!folder.exists()) {
                folder.mkdirs();
            }
        } else {
            /**
             * 不存在SD卡,就放到缓存文件夹内
             */
            root = application.getCacheDir();
            folder = new File(root, appName);
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }
        if (folderName != null) {
            folder = new File(folder, folderName);
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }
        return folder.getAbsolutePath();
    }

    /**
     * 获取圆角Bitmap
     *
     * @param srcBitmap
     * @param radius
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap srcBitmap, float radius) {
        Bitmap resultBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(resultBitmap);
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, srcBitmap.getWidth(), srcBitmap.getHeight());
        RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(0xBDBDBE);
        canvas.drawRoundRect(rectF, radius, radius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(srcBitmap, rect, rect, paint);
        return resultBitmap;
    }

    /**
     * 图片解析
     *
     * @param path
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static Bitmap decodeScaleImage(String path, int targetWidth, int targetHeight) {
        BitmapFactory.Options bitmapOptions = getBitmapOptions(path);
        bitmapOptions.inSampleSize = calculateInSampleSize(bitmapOptions, targetWidth, targetHeight);
        bitmapOptions.inJustDecodeBounds = false;
        Bitmap noRotatingBitmap = BitmapFactory.decodeFile(path, bitmapOptions);
        int degree = readPictureDegree(path);
        Bitmap rotatingBitmap;
        if (noRotatingBitmap != null && degree != 0) {
            rotatingBitmap = rotatingImageView(degree, noRotatingBitmap);
            noRotatingBitmap.recycle();
            return rotatingBitmap;
        } else {
            return noRotatingBitmap;
        }
    }

    /**
     * 获取缩略图
     *
     * @param path
     * @param targetWidth
     * @return
     */
    public static String getThumbnailImage(String path, int targetWidth) {
        Bitmap scaleImage = decodeScaleImage(path, targetWidth, targetWidth);
        try {
            File file = File.createTempFile("image", ".jpg");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            scaleImage.compress(Bitmap.CompressFormat.JPEG, 60, fileOutputStream);
            fileOutputStream.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return path;
        }
    }

    /**
     * 图片解析
     *
     * @param context
     * @param resId
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static Bitmap decodeScaleImage(Context context, int resId, int targetWidth, int targetHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resId, options);
        options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId, options);
        return bitmap;
    }

    /**
     * 计算样本大小
     *
     * @param options
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int targetWidth, int targetHeight) {
        int height = options.outHeight;
        int width = options.outWidth;
        int scale = 1;
        if (height > targetHeight || width > targetWidth) {
            int heightScale = Math.round((float) height / (float) targetHeight);
            int widthScale = Math.round((float) width / (float) targetWidth);
            scale = heightScale > widthScale ? heightScale : widthScale;
        }
        return scale;
    }

    /**
     * 获取BitmapFactory.Options
     *
     * @param pathName
     * @return
     */
    public static BitmapFactory.Options getBitmapOptions(String pathName) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, opts);
        return opts;
    }

    /**
     * 获取图片角度
     *
     * @param filename
     * @return
     */
    public static int readPictureDegree(String filename) {
        short degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(filename);
            int anInt = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
            switch (anInt) {
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                case ExifInterface.ORIENTATION_TRANSPOSE:
                case ExifInterface.ORIENTATION_TRANSVERSE:
                default:
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return degree;
    }

    /**
     * 旋转ImageView
     *
     * @param degree
     * @param source
     * @return
     */
    public static Bitmap rotatingImageView(int degree, Bitmap source) {
        Matrix matrix = new Matrix();
        matrix.postRotate((float) degree);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }

    /**
     * 获取视频缩略图
     *
     * @param filePath
     * @param width
     * @param height
     * @param kind
     * @return
     */
    public static Bitmap getVideoThumbnail(String filePath, int width, int height, int kind) {
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(filePath, kind);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    /**
     * 保存视频缩略图
     *
     * @param file
     * @param width
     * @param height
     * @param kind
     * @return
     */
    public static String saveVideoThumbnail(File file, int width, int height, int kind) {
        Bitmap videoThumbnail = getVideoThumbnail(file.getAbsolutePath(), width, height, kind);
        File thumbFile = new File(PathUtil.getInstance().getVideoPath(), "th" + file.getName());
        try {
            thumbFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(thumbFile);
        } catch (FileNotFoundException var10) {
            var10.printStackTrace();
        }
        videoThumbnail.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
        try {
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileOutputStream.close();
        } catch (IOException var8) {
            var8.printStackTrace();
        }
        return thumbFile.getAbsolutePath();
    }

    /**
     * Image resource ID was converted into a byte [] data
     * 图片资源ID 转换 为 图片 byte[] 数据
     *
     * @param context
     * @param imageResourceId
     * @return
     */
    public static byte[] toByteArray(Context context, int imageResourceId) {
        Bitmap bitmap = ImageUtil.toBitmap(context, imageResourceId);
        if (bitmap != null) {
            return ImageUtil.toByteArray(bitmap);
        } else {
            return null;
        }
    }

    /**
     * ImageView getDrawable () into a byte [] data
     * ImageView的getDrawable() 转换为 byte[] 数据
     *
     * @param imageView
     * @return
     */
    public static byte[] toByteArray(ImageView imageView) {
        Bitmap bitmap = ImageUtil.toBitmap(imageView);
        if (bitmap != null)
            return ImageUtil.toByteArray(bitmap);
        else {
            Log.w(ImageUtil.TAG,
                    "the ImageView imageView content was invalid");
            return null;
        }
    }

    /**
     * byte [] data type conversion for Bitmap data types
     * byte[]数据类型转换为 Bitmap数据类型
     *
     * @param imageData
     * @return
     */
    public static Bitmap toBitmap(byte[] imageData) {
        if ((imageData != null) && (imageData.length != 0)) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                    imageData.length);
            return bitmap;
        } else {
            Log.w(ImageUtil.TAG, "the byte[] imageData content was invalid");
            return null;
        }
    }

    /**
     * Image resource ID is converted to Bitmap type data
     * 资源ID 转换为 Bitmap类型数据
     *
     * @param context
     * @param imageResourceId
     * @return
     */
    public static Bitmap toBitmap(Context context, int imageResourceId) {
        // 将图片转化为位图
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
                imageResourceId);
        if (bitmap != null) {
            return bitmap;
        } else {
            Log.w(ImageUtil.TAG,
                    "the int imageResourceId content was invalid");
            return null;
        }
    }

    /**
     * ImageView types into a Bitmap
     * ImageView类型转换为Bitmap
     *
     * @param imageView
     * @return
     */
    public static Bitmap toBitmap(ImageView imageView) {
        if (imageView.getDrawable() != null) {
            Bitmap bitmap = ImageUtil.toBitmap(imageView.getDrawable());
            return bitmap;
        } else {
            return null;
        }
    }

    /**
     * Bitmap type is converted into a image byte [] data
     * Bitmap类型 转换 为图片 byte[] 数据
     *
     * @param bitmap
     * @return
     */
    public static byte[] toByteArray(Bitmap bitmap) {
        if (bitmap != null) {
            int size = bitmap.getWidth() * bitmap.getHeight() * 4;
            // 创建一个字节数组输出流,流的大小为size
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
                    size);
            // 设置位图的压缩格式,质量为100%,并放入字节数组输出流中
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    byteArrayOutputStream);
            // 将字节数组输出流转化为字节数组byte[]
            byte[] imageData = byteArrayOutputStream.toByteArray();
            return imageData;
        } else {
            Log.w(ImageUtil.TAG,
                    "the Bitmap bitmap content was invalid");
            return null;
        }

    }

    /**
     * Drawable type into a Bitmap
     * Drawable 类型转换为 Bitmap类型
     *
     * @param drawable
     * @return
     */
    public static Bitmap toBitmap(Drawable drawable) {
        if (drawable != null) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            return bitmap;
        } else {
            Log.w(ImageUtil.TAG,
                    "the Drawable drawable content was invalid");
            return null;
        }
    }

    /**
     * Bitmap type into a Drawable
     * Bitmap 类型转换为 Drawable类型
     *
     * @param bitmap
     * @return
     */
    public static Drawable toDrawable(Bitmap bitmap) {
        if (bitmap != null) {
            Drawable drawable = new BitmapDrawable(bitmap);
            return drawable;
        } else {
            Log.w(ImageUtil.TAG,
                    "the Bitmap bitmap content was invalid");
            return null;
        }
    }

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-25 15:01:41

24.Android 图片工具ImageUtil的相关文章

Android 调节图片工具类

package com.base.changeimage; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; /** * 调节图

android 图片处理工具类

图片工具类,可用于Bitmap, byte array, Drawable之间进行转换以及图片缩放,目前功能薄弱,后面会进行增强.如: bitmapToDrawable(Bitmap b) bimap转换为drawable drawableToBitmap(Drawable d) drawable转换为bitmap drawableToByte(Drawable d) drawable转换为byte scaleImage(Bitmap org, float scaleWidth, float s

【转】Android开发工具--android-studio-bundle-141.2288178

原文网址:http://www.androiddevtools.cn/ AndroidDevTools简介 Android Dev Tools官网地址:www.androiddevtools.cn 收集整理Android开发所需的Android SDK.开发中用到的工具.Android开发教程.Android设计规范,免费的设计素材等. 欢迎大家推荐自己在Android开发过程中用的好用的工具.学习开发教程.用到设计素材,欢迎Star.Fork ?. 如果你对翻译英文的Android开发技术文章

拍照、本地图片工具类(兼容至Android7.0)

拍照.本地图片工具类:解决了4.4以上剪裁会提示"找不到文件"和6.0动态授予权限,及7.0报FileUriExposedException异常问题. package com.hb.weex.util; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.content.ClipData; import android.content.Conten

一起写一个Android图片加载框架

本文会从内部原理到具体实现来详细介绍如何开发一个简洁而实用的Android图片加载缓存框架,并在内存占用与加载图片所需时间这两个方面与主流图片加载框架之一Universal Image Loader做出比较,来帮助我们量化这个框架的性能.通过开发这个框架,我们可以进一步深入了解Android中的Bitmap操作.LruCache.LruDiskCache,让我们以后与Bitmap打交道能够更加得心应手.若对Bitmap的大小计算及inSampleSize计算还不太熟悉,请参考这里:高效加载Bit

android图片处理方法(不断收集中)

//压缩图片大小 public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while ( baos.toByteArra

android图片处理方法(转)

//压缩图片大小 public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while ( baos.toByteArra

Android图片裁剪——自定义裁剪工具

上次弄完调用系统裁剪之后,我又试着做一个自定义的裁剪工具. 老习惯,文章开始前还是先把我参考的资料贴出来.您愿意节省点时间看别人的更好的就直接从下面链接跳走-愿意看看我怎么做的那就先谢谢了! GitHub上老外做的一个非常棒的demo,代码也很漂亮 android自定义view实现裁剪图片功能,不使用系统的 第一个链接代码写的太好了,不过很多我用不上,也不需要那么麻烦的文件结构:第二个代码比较简单,但有些地方还是有借鉴意义的. 下面是我的代码,时间紧,就先不写太详细了: 注意几点: 我是在平板上

Android 图片处理方法

//压缩图片大小 public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while ( baos.toByteArra