Android Code Snippet [B4X] Create square Thumbnail

CreateSquareThumbnail:
Sub CreateSquareThumbnail(Input As B4XBitmap) As B4XBitmap
    If Input.Width <> Input.Height Then
        'if the image is not square then we crop it to be a square.
        Dim l As Int = Min(Input.Width, Input.Height)
        Return Input.Crop(Input.Width / 2 - l / 2, Input.Height / 2 - l / 2, l, l)
    Else
        Return Input
    End If
End Sub
Usage:
CreateSquareThumbnail(xui.LoadBitmapResize(File.DirAssets,"Snapchat-248558753.jpg",150dip,150dip,True))
 
Last edited:

Alexander Stolte

Expert
Licensed User
Longtime User
Shouldn't it be used to reduce the size of an image? (or, better, to return a miniature of an image)
But before you can do that, you need a square ;)

I see that if the input image is square the routine does not perform the "transformation". It seems more a routine to square an image rather than a "transformation" to thumbnail.
So I wrote this example:
 

Alexander Stolte

Expert
Licensed User
Longtime User
B4X:
CreateThumbnail(xui.LoadBitmapResize(File.DirAssets,"Snapchat-248558753.jpg",150dip,150dip,True))
The clue is to load the image already in the target size. (150dip,150dip)
 

LucaMs

Expert
Licensed User
Longtime User
B4X:
    Dim xBitmap As B4XBitmap
    ' help.png is squared, 96x96px
    xBitmap = xui.LoadBitmap(File.DirAssets, "help.png")
    Log("Size: " & xBitmap.Width & TAB & xBitmap.Height)

    Dim xThumbnail As B4XBitmap
    xThumbnail = CreateThumbnail(xBitmap)
    Log("Size: " & xThumbnail.Width & TAB & xThumbnail.Height)

Waiting for debugger to connect...
Program started.
Size: 96 96
Size: 96 96
 

Alexander Stolte

Expert
Licensed User
Longtime User
1590672771136.png

it's in the title.
 

LucaMs

Expert
Licensed User
Longtime User
Last edited:

Alexander Stolte

Expert
Licensed User
Longtime User
just have a look in your gallery, large images are cut out in the middle and are then the thumbnails. that's exactly what this function does, just turn a non-square image into a square without it looking stupid
 

LucaMs

Expert
Licensed User
Longtime User
just have a look in your gallery, large images are cut out in the middle and are then the thumbnails. that's exactly what this function does, just turn a non-square image into a square without it looking stupid
Yes, but If I pass a B4XBitmap 1500x1000, your routine returns a 1000x1000 bitmap (squared, centered, useful), not a small one to use as thumbnail (say 100x100).

To be a "CreateSquareThumbnail" it should also reduce the size. You should pass (and use, of course) other parameters, like SideSize and / or ReducingFactor (or change its name, because my new 1000x1000 B4XBitmap cannot be called "thumbnail", for sure.
 
Top