打印图像中的NUll指针异常

时间:2012-01-06 04:29:07

标签: android printing

public static File saveCanvasPictureToTempFile( Picture picture )
{
    File tempFile = null;

    // save to temporary file
    File dir = getTempDir();
    if( dir != null )
    {
        FileOutputStream fos = null;
        try
        {
            File f = File.createTempFile( "picture", ".stream", dir );
            fos = new FileOutputStream( f );
            picture.writeToStream( fos );
            tempFile = f;
        }
        catch( IOException e )
        {
            Log.e( TAG, "failed to save picture", e );
        }
        finally
        {
            close( fos );
        }
    }       

    return tempFile;
}

此代码应该创建一个临时文件并将其返回给Main活动,但该文件在主活动中给出了一个空指针异常。我可能做错了什么?

我的主要活动的代码是

void printCanvasAsBitmapExample()
{
    // create canvas to render on
    Bitmap b = Bitmap.createBitmap( 240, 240, Bitmap.Config.RGB_565 );
    Canvas c = new Canvas( b );

    // fill background with WHITE
    c.drawRGB( 0xFF, 0xFF, 0xFF );

    // draw text
    Paint p = new Paint();
    Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
    p.setTextSize( 18 );
    p.setTypeface( font );
    p.setAntiAlias(true);       
    Rect textBounds = new Rect();
    p.getTextBounds( HELLO_WORLD, 0, HELLO_WORLD.length(), textBounds );
    int x = (c.getWidth() - (textBounds.right-textBounds.left)) / 2;
    int y = (c.getHeight() - (textBounds.bottom-textBounds.top)) / 2;
    c.drawText( HELLO_WORLD, x, y, p );

    // draw icon
    Bitmap icon = BitmapFactory.decodeResource( getResources(), R.drawable.icon );
    c.drawBitmap( icon, 0, 0, null );

    // queue bitmap for printing
    try
    {
        File f = PrintUtils.saveBitmapToTempFile( b, Bitmap.CompressFormat.PNG );
        if( f != null )
        {
            PrintUtils.queueBitmapForPrinting( this, f, Bitmap.CompressFormat.PNG );
        }
    }
    catch( Exception e )
    {
        Log.e( TAG, "failed to save/queue bitmap", e );
    }
}

1 个答案:

答案 0 :(得分:1)

您的错误可能是由于使用了fos = new FileOutputStream(f)而不是Android使用fos = [context instance].openFileOutput(filename, mode)的特定方式。

可能是您无权写信tempDir,因此您获得了NullPointerException

请参阅documentation。它非常清楚地说明了这一点。