Search code examples
apache-flexactionscriptairimage-scaling

Actionscript/Air/Flex 4 - Load Image from File, Scale Down, and Save as PNG


I wrote these functions which I use in conjunction to scale down some BitmapData and save it as a PNG. However, the scaledImage.draw(originalImage, scalingMatrix, null, null, null, true); line with smoothing set to true does not have the intended smoothing effect when I save the bitmap data as a PNG using the second function. The resulting image file is not antialiased at all. Is there anything I'm doing wrong here? Thanks!

    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();                
    }       

Solution

  • Turns out this code was working. It was saving smoothed images. It wasn't apparent because the images I was scaling down were ~20K x 20K pixels so jaggies appeared anyway with smoothing. Smoothing was apparent with more "normal" sized images like 2K x 2K pixels