如何在一个巨大的位图上写文字

时间:2014-09-04 13:55:00

标签: android memory canvas bitmap out-of-memory

我正在编写一个简单的相机应用程序,让用户拍照,应用程序会将一些信息写入图像。

我出现内存错误,因为图像可能很大。取决于相机硬件。

这就是我将文字写入图像的方式:

public static byte[] writeTextOnImage(byte[] imgData, String text) {
    Bitmap bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
    Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.RGB_565, true);

    Canvas canvas = new Canvas(mutableBitmap);
    Paint paint = new Paint();

    int dist = 30;
    Rect areaRect = new Rect(dist, mutableBitmap.getHeight() - dist, 170, (int) (mutableBitmap.getHeight() - dist * 1.6f));

    paint.setColor(Color.BLACK);
    canvas.drawRect(areaRect, paint);

    RectF bounds = new RectF(areaRect);
    bounds.right = paint.measureText(text, 0, text.length());
    bounds.bottom = paint.descent() - paint.ascent();

    bounds.left += (areaRect.width() - bounds.right) / 2.0f;
    bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;

    paint.setColor(Color.WHITE);
    canvas.drawText(text, bounds.left, bounds.top - paint.ascent(), paint);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}

我想我甚至不应该考虑加载整个图像,但我还是要以某种方式写它。是否可以编辑图像文件而不将其全部加载到内存中?

1 个答案:

答案 0 :(得分:0)

您可以在NDK中操作图像。本机代码可用的内存仅受设备RAM的限制。缺点是您必须使用本机代码解码图像。