B4J Question How to resize a .PNG from a PNG bytearray without writing to disk?

MathiasM

Active Member
Licensed User
Hello

I want to resize a PNG image which is stored in a bytearray without writing it to disk.
How would this be possible?
I was thinking of transforming the bytearray to a bitmap for resizing, but initializing a bitmap from a bytearray doesn't seem to be possible.

Anyone has an idea?

Thanks!
 

emexes

Expert
Licensed User
for B4A not B4J, but... worth trying anyway

using "As Image" rather than "As Bitmap" and probably also have to change variable name "Image" to eg "img"

I've added the two code snippets to the second post.
B4X:
Public Sub ImageToBytes(Image As Bitmap) As Byte()
   Dim out As OutputStream
   out.InitializeToBytesArray(0)
   Image.WriteToStream(out, 100, "JPEG")
   out.Close
   Return out.ToBytesArray
End Sub

Public Sub BytesToImage(bytes() As Byte) As Bitmap
   Dim In As InputStream
   In.InitializeFromBytesArray(bytes, 0, bytes.Length)
   Dim bmp As Bitmap
   bmp.Initialize2(In)
   Return bmp
End Sub
 
Last edited:
Upvote 0

MathiasM

Active Member
Licensed User
Hi @emexes, Thanks for pointing me in the right direction, I had no idea one could initialize an Inputstream from a ByteArray. Very nice.
I'm new to Image programming and was unaware B4J had no Bitmap class. I used the Image class instead. IThat doesn't seem to have a Crop or Resize function.

I tried making my own Crop function, It works. The disksize of the cropped image is greater than the original image because of the added alpha channel though.
Have to figure that out.

This is my final code (for future reference)

CropImage:
Sub CropImage(originalImage As Image, width As Int, height As Int) As Image
    bc.Initialize(width, height)
    For i = 0 To width - 1
        For j = 0 To height - 1
            Dim color As Int = originalImage.GetPixel(i, j)
            bc.SetColor(i, j, color)
        Next
    Next
    Return bc.Bitmap
End Sub

Usage while reading from a buffer:

B4X:
Dim img() As Byte = awt.ScreenCaptureAsByteArray

Dim ogImage As Image
Dim ips As InputStream
ips.InitializeFromBytesArray(img, 0, img.Length -1)
ogImage.Initialize2(ips)

Dim croppedImg As Image = CropImage(ogImage, 1535, 863)
Dim Out As OutputStream = File.OpenOutput(File.DirApp, "cropped.png", False)
cropperImg.WriteToStream(Out)
Out.Close
 
Upvote 0
Top