iOS Code Snippet Image Resize and Save

Hi,

After struggling for a while with this and with the help of nice people in this forum I finally solved it and now I want to share the code :)

Sub Call Examples:
B4X:
    ''''''''''' RESIZE EXAMPLE ''''''''''
    Dim MyOrigImage As Bitmap
    Dim MyDestImage As Bitmap
   
    MyOrigImage.Initialize(File.DirAssets,"B4i_Logo.png")
    MyDestImage = ResizeImage(MyOrigImage, 1024, 768)
   
    ''''''''''' SAVE EXAMPLE ''''''''''
    Dim Success As Boolean
    Success = SaveImage(MyDestImage, "B4i_NewSize",File.DirDocuments,100)
    If Success <> True Then
        ' SHOW ERROR MSG
    End If
And now the Subs:
B4X:
Sub ResizeImage (Image As Bitmap, Width As Int, Height As Int) As Bitmap
    Dim PhotoCanvas As Canvas
    Dim PhotoPanel As Panel
    Dim PhotoView As ImageView
    Dim NewImage As Bitmap
   
    PhotoPanel.Initialize("")
    PhotoPanel.Width = Width / 2
    PhotoPanel.Height = Height / 2
   
    PhotoView.Initialize("")
    PhotoView.Bitmap = Image
   
    PhotoPanel.AddView(PhotoView,0,0,Width / 2,Height / 2)

    PhotoCanvas.Initialize(PhotoPanel)
    NewImage = PhotoCanvas.CreateBitmap
   
    Return NewImage
End Sub

B4X:
Sub SaveImage (Image As Bitmap, Filename As String, Dir As String, Quality As Int) As Boolean
    Dim Result As Boolean= True
    Dim out As OutputStream = File.OpenOutput(Dir, Filename, False)
    Dim data() As Byte = GetByteFromBitmap(Image, Quality)
    Try
        out.WriteBytes(data, 0, data.Length)
    Catch
        Result = False
    End Try
    out.Close
    Return Result
End Sub

B4X:
Sub GetByteFromBitmap(img As Bitmap, Quality As Int) As Byte()
      Dim out As OutputStream
      Dim data() As Byte
      out.InitializeToBytesArray(1)
      img.WriteToStream(out,Quality,"JPEG")
      data = out.ToBytesArray
      out.Close
      Return data
End Sub

I hope you find this useful :)

Greets!
 

Attachments

  • Image Resize and Save.zip
    23.9 KB · Views: 489

jaraiza

Active Member
Licensed User
Longtime User
Thank you for sharing. Why did you add the Try block there?

In most cases it is better not to catch errors and instead let the developer that uses your code (or library) to handle the error.

I added Try/Catch because if anyone uses the Subs "as is" they'll get a false if "out.WriteBytes(data, 0, data.Length)" fails. I did this because GoDaddy tends to change folder attributes and I got crazy finding the faulty code until I realized it was not my fault :) But any experienced coder can customize their own error handling :)
 
Top