Actionscript / Air / Flex 4 - 从文件加载图像,缩小和保存为PNG

时间:2010-12-27 05:00:14

标签: flex actionscript air image-scaling

我写了这些函数,我一起使用它来缩小一些BitmapData并将其保存为PNG。但是,当我使用第二个函数将位图数据保存为PNG时,平滑设置为true的scaledImage.draw(originalImage, scalingMatrix, null, null, null, true);行没有预期的平滑效果。生成的图像文件根本没有抗锯齿。我有什么问题吗?谢谢!

    public static function scaleImage(originalImage:BitmapData, size:int):BitmapData
    {
        // Calculate the scaled size.
        var scale:Number;
        var scaledWidth:Number;
        var scaledHeight:Number;

        if (originalImage.width > originalImage.height)
        {
            scale = (size as Number) / (originalImage.width as Number);
            scaledWidth = size;
            scaledHeight = originalImage.height * scale;
        }
        else
        {
            scale = (size as Number) / (originalImage.height as Number);
            scaledHeight = size;
            scaledWidth = originalImage.width * scale;
        }

        var scalingMatrix:Matrix = new Matrix();
        scalingMatrix.scale(scale, scale);

        // Scale the image.
        var scaledImage:BitmapData = new BitmapData(scaledWidth, scaledHeight, true, 0x00000000);
        scaledImage.draw(originalImage, scalingMatrix, null, null, null, true);

        return scaledImage;
    }

    public static function saveImageAsPNG(image:BitmapData, imageFile:File):void
    {
        // Encode the image as a PNG.
        var pngEncoder:PNGEncoder = new PNGEncoder();
        var imageByteArray:ByteArray = pngEncoder.encode(image);

        // Write the image data to a file.
        var imageFileStream:FileStream = new FileStream();
        imageFileStream.open(imageFile, FileMode.WRITE);
        imageFileStream.writeBytes(imageByteArray);
        imageFileStream.close();                
    }       

1 个答案:

答案 0 :(得分:0)

原来这个代码正常运行。它节省了平滑的图像。这一点并不明显,因为我缩小的图像大约是20K x 20K像素,所以无论如何都会出现锯齿状的平滑现象。使用更多“正常”尺寸的图像(如2K x 2K像素)可以看到平滑效果