安卓上传服务器图片处理

在上传图片到服务器时要对图片进行处理然后上传到服务器



根据需要的图片的尺寸 对图片进行压缩,当原图片小于需要的尺寸时直接返回原图的bitmap

/**
 * bitmap  处理
 *
 * @param path   文件路径
 * @param width  处理后宽度
 * @param height 处理后高度
 * @return 处理后的bitmap
 */
public static Bitmap resetBitmap(String path, float width, float height) {

    InputStream is = null;
    InputStream is1 = null;

    try {
        is = new FileInputStream(new File(path));
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, options);

        is1 = new FileInputStream(new File(path));

        if (width >= options.outWidth || height >= options.outHeight) {
            return BitmapFactory.decodeStream(is1, null, null);
        }

        int widthRate = Math.round(options.outWidth / width);
        int heightRate = Math.round(options.outHeight / height);

        BitmapFactory.Options options1 = new BitmapFactory.Options();

        options1.inJustDecodeBounds = false;
        options1.inSampleSize = Math.min(widthRate, heightRate);

        return BitmapFactory.decodeStream(is1, null, options1);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
            is1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

将上一个方法的bitmap写到内存中  从内存中读取bitmap的byte[]  数据 ,将byte[]数组传到服务器  我这里用的retrofit 框架 上传可以直接传byte[] 数组


/**
 * 将bitmap  转化为byte[]  数据
 *
 * @param bitmap
 * @return
 */
public static byte[] toByte(Bitmap bitmap) {

    byte[] bytes = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        bytes = byteArrayOutputStream.toByteArray();
        if (bytes != null && bytes.length > 0) {
            return bytes;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

这样可以避免将压缩后的图片在写到内存卡  再上传文件




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值