【问题标题】:How to set Limit Upload Image from Android to Database MySQL如何设置限制从 Android 上传图像到数据库 MySQL
【发布时间】:2017-05-07 02:47:11
【问题描述】:

先生,我有问题,当我想以 KB(千字节)为单位将 LIMIT 设置为 UPLOAD IMAGE 时,例如 200KB。

private void uploadImage(){
    if (bitmap.getByteCount() > 7 * 1024 * 1024){
        H.T(AddFotoActivity.this,"Image Maks 200KB");
    }
}

我尝试了该代码,但是我只能上传 110KB,而当我尝试上传 116KB 时却无法上传。 先生如何上传200KB的文件?不知道怎么计算7*1024*1024

【问题讨论】:

  • 1024 字节为 1 KB。所以 200kB * 1024B = 204800 字节
  • 但是,位图在内存中比图像文件大。所以很可能一个 200k 的图像文件,当它作为位图打开时会更多。

标签: android mysql


【解决方案1】:

试试这个代码:

/**
 * reduces the size of the image
 * @param image
 * @param maxSize
 * @return
 */
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();

    float bitmapRatio = (float)width / (float) height;
    if (bitmapRatio > 0) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
}

像这样使用它:

Bitmap scaledImage = getResizedBitmap(photo, 300); //here 300 is maxsize

来自Wikipedia

对于最高质量的图像 (Q=100),每个颜色像素需要大约 8.25 位

因此,对于 300x300 图像上的 Q=100,这将导致 (300 * 300) px * 8.25 bits/px = 741,500 bits = ~ 91 kB,这肯定小于 200KB

你也可以尝试其他维度..

您也可以尝试使用位图制作图像并比较图像的实际大小..

代码如下:

 //create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

【讨论】:

  • 您的代码用于调整宽度和高度。所以这并不意味着 200k 文件调整大小......另外,我认为他在问另一个问题......
  • 好吧,我可能错了......但在投反对票之前先看看这个stackoverflow.com/questions/16954109/…
  • 好的@rafsanahmad007 然后链接答案,不要只复制代码。
  • 虽然他在问如何计算大小和上传。与调整大小无关。
  • 那么设置限制上传图片200KB我该怎么办?
猜你喜欢
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 2013-09-21
  • 1970-01-01
  • 2016-07-21
  • 2018-08-10
相关资源
最近更新 更多