Android Question [SOLVED] Reduce image size before encoding, preferably without writing to disk.

jroriz

Active Member
Licensed User
Longtime User
B4X:
Dim base64con As Base64Convert
base64con.Initialize
dim encodedImg as string = base64con.EncodeFromImage(File.DirRootExternal, myfile)

I need to reduce the image size to a maximum width of 200 pixels.
It would be desirable to achieve this without involving writing to disk, because this portion of code is in a loop that will resize and encode multiple images.
 

TILogistic

Expert
Licensed User
Longtime User
?
Note:
The B4Xbitmap allows resize.
1713065784720.png

B4X:
        Dim Base64 As String, Bmp As B4XBitmap, SU As StringUtils
       
        'Image to Base64 (Resize).
        Base64 = SU.EncodeBase64(ImageToBytes(B4XSignature1.Bitmap.Resize(350, 350, True)))

        'Base64 to Image
        Bmp = BytesToImage(SU.DecodeBase64(Base64.Replace("data:image/jpeg;base64,", "")))
        B4XImageView1.Bitmap = Bmp
       
        'Image to file
        Dim Bmp As B4XBitmap = BytesToImage(SU.DecodeBase64(Base64))
        ImageToFile(Bmp, xui.DefaultFolder, "Signature", "PNG")

B4X:
'Image to bytes
Public Sub ImageToBytes(Image As B4XBitmap) As Byte()
    Dim Out As OutputStream
    Out.InitializeToBytesArray(0)
    Image.WriteToStream(Out, 100, "PNG")
    Out.Close
    Return Out.ToBytesArray
End Sub

'Bytes to Image
Public Sub BytesToImage(Bytes() As Byte) As B4XBitmap
    Dim In As InputStream
    In.InitializeFromBytesArray(Bytes, 0, Bytes.Length)
    #If B4A or B4i
    Dim Bmp as Bitmap :    Bmp.Initialize2(In)
    #Else
    Dim Bmp As Image : Bmp.Initialize2(In)
    #End If
    Return Bmp
End Sub

'Image to file
Public Sub ImageToFile(Bmp As B4XBitmap, Dir As String, Name As String, Format As String)
    Dim Out As OutputStream = File.OpenOutput(Dir, Name & "." & Format, False)
    Bmp.WriteToStream(Out, 100, Format)
    Out.Close
End Sub
 
Last edited:
Upvote 0
Top