1. 程式人生 > >java.lang.RuntimeException: Canvas: trying to use a non-premultiplied bitmap android.graphics.Bitma

java.lang.RuntimeException: Canvas: trying to use a non-premultiplied bitmap android.graphics.Bitma

java.lang.RuntimeException: Canvas: trying to use a non-premultiplied bitmap [email protected]

載入圖片的時候發現上述異常。程式碼如下:

public static FaceImage readImage(String file_name) {
        Log.i(TAG, "Read Image file: " + file_name);

        int SHOTER_SIDE=600;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inPremultiplied = false;
        Bitmap bitmap = BitmapFactory.decodeFile(file_name, options);
        Bitmap bitmap_final = bitmap;

        int oriWidth = bitmap.getWidth();
        int oriHeight = bitmap.getHeight();
        int shorter = oriWidth < oriHeight ? oriWidth:oriHeight;
        if (shorter > SHOTER_SIDE) {
            int height = SHOTER_SIDE;
            int width = SHOTER_SIDE;
            if (oriWidth < oriHeight) {
                height = (int)((float)oriHeight / oriWidth * width);
            } else {
                width = (int)((float)oriWidth / oriHeight * height);
            }
            bitmap_final =  Bitmap.createScaledBitmap(bitmap, width, height, false);
        }

        // Copy bitmap pixels to buffer
        ByteBuffer argb_buf = ByteBuffer.allocate(bitmap_final.getByteCount());
        bitmap_final.copyPixelsToBuffer(argb_buf);

        // Generate FaceImage
        byte[] bytes = argb_buf.array();

        byte[] image_data = new byte[bytes.length/4 * 3];
        for(int i = 0; i < bytes.length; i += 4) {
            int j = i / 4;
            image_data[j * 3 + 0] = (byte)(((int)(bytes[i + 2]))&0xFF);
            image_data[j * 3 + 1] = (byte)(((int)(bytes[i + 1]))&0xFF);
            image_data[j * 3 + 2] = (byte)(((int)(bytes[i + 0]))&0xFF);
        }

        FaceImage image = new FaceImage(bitmap_final.getWidth(), bitmap_final.getHeight(), 3, image_data);

        return image;
    }
發現是options.inPremultiplied = false出的問題。註釋掉就行了。