Trim spaces around transparent PNG

So, I managed to get myself stuck in a situation where you need to place a database with images on the stage (transparent images of various products), all of which must be aligned to the height of the product.

My problem is that the png products are “floating” and I can’t control where this happens in the png it will sit on (it can be tight at the top and the room below is loading, vice versa)

Does anyone know an existing way to know png 'true' height (width is optional). I thought about sorting through the data of the bitmap images and checking, but I wondered if someone had already invented this wheel?

eg Example with number above / Example with none, really

+3
source share
4 answers

In the end, I came up with the solution below, most likely not the most efficient way, but it works.

    /**
     * Cuts off the transparency around a bitmap, returning the true width and height whilst retaining transparency
     *  
     * @param input Bitmap
     * 
     */
    private function trimTransparency(input:BitmapData,colourChecker:uint = 0x00FF00):Bitmap {

        //Keep a copy of the original
        var orignal:Bitmap = new Bitmap(input);

        //Clone the orignal with a white background
        var clone:BitmapData = new BitmapData(orignal.width, orignal.height,true,colourChecker);
        clone.draw(orignal);

        //Grab the bounds of the clone checking against white
        var bounds:Rectangle = clone.getColorBoundsRect(colourChecker, colourChecker, false);

        //Create a new bitmap to return the changed bitmap
        var returnedBitmap:Bitmap = new Bitmap();
        returnedBitmap.bitmapData = new BitmapData(bounds.width, bounds.height,true,0x00000000);
        returnedBitmap.bitmapData.copyPixels(orignal.bitmapData,bounds, new Point(0,0));    
        return returnedBitmap;


    }
+1
source

you can use the BitmapData class method getColorBoundsRect () to get a rectangle of opaque content. The documentation also gives this example:

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html

Thanks Alistair

+6
source

, getColorBoundsRect .

, , getColorBoundsRect " 100% -". , BitmapData.threshold, .

I would do something like duplicate a bitmap, run the threshold method on it, turn all non-adhesive pixels bright green, and then run getColorBoundsRect, selecting all the green pixels you just created.

+3
source

This is the solution I came across, if necessary:

    public static function trimAlpha(source:BitmapData):BitmapData {
        var notAlphaBounds:Rectangle = source.getColorBoundsRect(0xFF000000, 0x00000000, false);
        var trimed:BitmapData = new BitmapData(notAlphaBounds.width, notAlphaBounds.height, true, 0x00000000);
        trimed.copyPixels(source, notAlphaBounds, new Point());
        return trimed;  
    }
+1
source

Source: https://habr.com/ru/post/1770948/


All Articles