Android Question Error loading bitmap : Initialize bitamp from input stream with php- mysql using OkhttpUtils2

lazreg

Active Member
Licensed User
Hi ..
i searched a lot before posting my question here and read many threads ,, but i coudn't solve this error
i got this error when i trying to Initialize bitamp ..

how i save my picture in mysql using OkhttpUtils2 :

B4X:
Sub btnAddCategory_Click
Dim bm  As Bitmap
bm.Initialize(File.DirAssets,"food.png")
Dim ImgBytes() As Byte = Module.ImageToBytes(bm)
Dim su As StringUtils
Dim imgData As String = su.EncodeBase64(ImgBytes)
Http.Initialize("InsertCategory", Me)
Log("Insert imgData " & imgData)
Http.PostString("https://xxxxxx/newCategory.php", "Category="&Module.SQLiteEscape(txtCategoryName.EditText.Text.Trim)&"&"&"cateory_pic="&imgData)
    Http.GetRequest.Timeout = 30000
'    Http.GetRequest.SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0")
'Http.GetRequest.SetContentType("image/png") ' image/png  application/json
 
End Sub
and this is ImageToBytes sub :

B4X:
Public Sub ImageToBytes(Image As Bitmap) As Byte()
    Dim out As OutputStream
    out.InitializeToBytesArray(0)
    Image.WriteToStream(out, 100, "PNG") 'JPEG
    ''''''out.Close
    Return out.ToBytesArray
End Sub
and the imgData string in log :

B4X:
Insert imgData iVBORw0KGgoAAAANSUhEUgAAApUAAAIsCAIAAAAs9sVNAAAAA3NCSVQICAjb4U/gAAAgAElEQVR4nFy9PY+1SZAsFJHVo7WwsPhNOFiYSEj35+LgISEEErgI4W6fisCIyDo9zN67O/O+3ec8T1VWZkTkR1HS//I//0//7//zf2PG9oCiKduGAQIQANi2AQCGbAIwLcOwYVsiCXvo/KygAW3ZBkzAAKx+iEEaIGmZw/ytSUqegZ2vF3ls5VFsEyAJ2KBtMr+HAQEAFDwQQJiERBgmCIA2METeLT9ugDBAM39h5BucRyUIwgZpYQ5tI08MeB+GGDC/BhMGhgQOoDwXSZIAMF3Rfk3/DTBISN4/tJkVQh+W7z36J+wD9Cn7h6T7D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wCRGSP7KJX1wRok392rIFXdwPZEuAeqp3Zajf45sHQ/VoAQLVk0JFmQRvvPSh7cvQpNgrAXy6s/MBBFxDjYsbJgRjbAu+tqZo1GGm9jV2lSRZzJMAgIjfbCuVI+eiKyJBhTKg6RZsykO2bmFcUFHWMimI+v9YjuXfJqIoLhCHSVzjgtf7kIHSXvD0JIQ9HnK1h3KHAMqGDjey/gHOIAK6E6OKNv7Qq+a+AE7fPEfUfXxj4lpIjccGPGewVv0SHE3Vb/QXwusOq+Jj6AMDH0JZzeUtk7OK4Kysfl1ack84ReY51xpUB2yym5cbtogJZPRCBW4qkLPmlpfTHx2CZYVdZ3r1CSbk5B+XNKvW1114nLmBrN/KKH/vB/sYyzeDehaXrDyQf0BCwbRrLHVCAT3BHzRwzkSYapK0/yde09nHf5FGC+DhRowck2G1r0YYNfx

and when i retrieve the picture from JobDone event

B4X:
For Each colroot As Map In categories
Dim category_name As String = colroot.Get("category_name")
Log("category_name : " & category_name)
Dim category_id As String = colroot.Get("category_id")
Log("category_id : " & category_id)
'///
Dim ImageData As String
Dim MyBitmap As Bitmap
Dim ImageBytes() As Byte
Dim su As StringUtils
Dim MyInputStream As InputStream
ImageData = colroot.Get("category_pic")
Log("ImageData size : " & ImageData.Length)
If ImageData <> Null And ImageData.Length >1 Then
Log("ImageData : " & ImageData)
ImageBytes = su.DecodeBase64(ImageData)'.SubString(25)
''Log("ImageData : " & ImageData.SubString(25))
MyBitmap=Module.BytesToImage(ImageBytes)
'Log("ImageData.SubString(4) : " & ImageData)
'LV.AddSingleLine2("  " & category_name,category_id )  '  MyBitmap
LV.AddTwoLinesAndBitmap2(category_name,category_id,MyBitmap,category_id)
' imgLogo.Bitmap = MyBitmap
End If
Next

and this is BytesToImage sub :

B4X:
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)
    In.Close
    Return bmp
End Sub
and the retrie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9rTaQ9XsIWYH6HOBTDw0QE4nhesJhhrzO8tOjJet5/QGkREOt5ZTN8BkAMcTNG83EGcfeDiDYxIly9N0gZE1XCvQYX/rnuPXCE3HRLUExkHziI/fTPBwV9D3hsrrdpglYodUYBXHkwT6wh2MMfAEKSvYIX4mx1mXDuBNr5A/4KeLYHFzBiNehUbpfsWqx4g94e1b9fOOAlzjlvrjvrQuR/eJ05HcUYkDOMqIJvnivL6TkHf5I9fN2EmhnUDSNJWTceJ3PaPIgzx7GzDjre61obqI1VcgNNC9efgzQGjtWEz5Xx1 DC/2yruBv5hKyLSsbKn1ugbOvVJWIMlUYQTj6B/I5gKEjU55KaGJS46rvoC9wCRGSP7KJX1wRok392rIFXdwPZEuAeqp3Zajf45sHQ/VoAQLVk0JFmQRvvPSh7cvQpNgrAXy6s/MBBFxDjYsbJgRjbAu tqZo1GGm9jV2lSRZzJMAgIjfbCuVI eiKyJBhTKg6RZsykO2bmFcUFHWMimI v9YjuXfJqIoLhCHSVzjgtf7kIHSXvD0JIQ9HnK1h3KHAMqGDjey/gHOIAK6E6OKNv7Qq a AE7fPEfUfXxj4lpIjccGPGewVv0SHE3Vb/QXwusOq Jj6AMDH0JZzeUtk7OK4Kysfl1ack84ReY51xpUB2yym5cbtogJZPRCBW4qkLPmlpfTHx2CZYVdZ3r1CSbk5B XNKvW1114nLmBrN/KKH/vB/sYyzeDehaXrDyQf0BCwbRrLHVCAT3BHzRwzkSYapK0/yde09nHf5FGC DhRowck2G1r0YYNfxXQp

i got this error
B4X:
java.lang.RuntimeException: Error loading bitmap.
in this line :
B4X:
    bmp.Initialize2(In)
category_pic is a blob ..

i didn't think it's a corrupt image coz i got the same string ..
please any help or suggestions ?
thanks a lot..
 
Last edited:

KMatle

Expert
Licensed User
The Base64 string looks strange (first chars and spaces later). Are you using UTF8 encoding in your php script? How do you insert the pic?
 

lazreg

Active Member
Licensed User
yes ,, i'm using UTF8 encoding...

my php script
B4X:
<?php

include ("db.php");

$con = mysql_connect($host,$user,$pw) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES 'utf8'");


        $Category = mysql_real_escape_string($_POST["Category"]);
       $category_pic= mysql_real_escape_string($_POST["cateory_pic"]);
       //echo $category_pic ;
        $q = mysql_query("SELECT * FROM categories WHERE category_name = '$Category'");
        $count = mysql_num_rows($q);
       //print json_encode ($count);
        if ($count == 0)
            {
              $res = mysql_query("INSERT INTO categories (category_name,category_pic,deleted) VALUES ('$Category','$category_pic','0')");
            print json_encode ("Inserted");
            }
        else
       {
            print json_encode ("Duplicated");
       }
mysql_close($con);

?>
 

lazreg

Active Member
Licensed User
@Erel
and when i retrieve the picture from JobDone event

B4X:
For Each colroot As Map In categories
Dim category_name As String = colroot.Get("category_name")
Log("category_name : " & category_name)
Dim category_id As String = colroot.Get("category_id")
Log("category_id : " & category_id)
'///
Dim ImageData As String
Dim MyBitmap As Bitmap
Dim ImageBytes() As Byte
Dim su As StringUtils
Dim MyInputStream As InputStream
ImageData = colroot.Get("category_pic")
Log("ImageData size : " & ImageData.Length)
If ImageData <> Null And ImageData.Length >1 Then
Log("ImageData : " & ImageData)
ImageBytes = su.DecodeBase64(ImageData)'.SubString(25)
''Log("ImageData : " & ImageData.SubString(25))
MyBitmap=Module.BytesToImage(ImageBytes)
'Log("ImageData.SubString(4) : " & ImageData)
'LV.AddSingleLine2("  " & category_name,category_id )  '  MyBitmap
LV.AddTwoLinesAndBitmap2(category_name,category_id,MyBitmap,category_id)
' imgLogo.Bitmap = MyBitmap
End If
Next
 

lazreg

Active Member
Licensed User
and this is BytesToImage sub :

B4X:
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)
    In.Close
    Return bmp
End Sub
 

Erel

Administrator
Staff member
Licensed User
I still don't see it. Where is a call to Job.GetString? What are you doing with MyInputStream?
 

lazreg

Active Member
Licensed User
ahh ,, ok ,, that's is

MyInputStream
just ignore ,i forgot to comment it,, there is a sub convert bytes to image
B4X:
Sub JobDone (Job As HttpJob)
    ProgressDialogHide
    If Job.Success Then
        Dim res As String, action As String
        res = Job.GetString
        Log("Back from Job:" & Job.JobName  & ", Success = " & Job.Success)
        Log("Response from server: " & res)

        Dim parser As JSONParser
        parser.Initialize(res)
  
        Select Job.JobName

Case "DispCategory"
                '///////////////////////////////
                LV.Clear
                Dim categories As List
                categories = parser.NextArray 'returns a list with maps
              
                SV.Panel.Height= categories.Size * 75dip  +715dip 'LV.Height+1000dip
                LV.Height=  SV.Panel.Height' 300%y 'rs.RowCount * 75dip +300dip
                  
                For Each colroot As Map In categories
                    Dim category_name As String = colroot.Get("category_name")
                    Log("category_name : " & category_name)
                    Dim category_id As String = colroot.Get("category_id")
                    Log("category_id : " & category_id)
                  
                    '///
                    Dim ImageData As String
                    Dim MyBitmap As Bitmap
                    Dim ImageBytes() As Byte
                    Dim su As StringUtils
                    Dim MyInputStream As InputStream

                    ImageData = colroot.Get("category_pic")
                    Log("ImageData size : " & ImageData.Length)

                    If ImageData <> Null And ImageData.Length >1 Then
                        Log("ImageData : " & ImageData)

                        ImageBytes = su.DecodeBase64(ImageData)'.SubString(25)
                        ''Log("ImageData : " & ImageData.SubString(25))
                      
                        MyBitmap=Module.BytesToImage(ImageBytes)
                      
                        'Log("ImageData.SubString(4) : " & ImageData)

                    'LV.AddSingleLine2("  " & category_name,category_id )  '  MyBitmap
                        LV.AddTwoLinesAndBitmap2(category_name,category_id,MyBitmap,category_id)
                        ' imgLogo.Bitmap = MyBitmap
                    End If
                Next
                  
              
                '////////////////////////////////
        End Select
    Else
        Log("Job.Success: " & Job.Success)
        Log("Error: " & Job.ErrorMessage)
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub
 
Last edited:

Erel

Administrator
Staff member
Licensed User
My guess is that mysql_real_escape_string breaks the base 64 string.

You can try to replace spaces with + when you receive the string.
 

lazreg

Active Member
Licensed User
the first line retrieved the stored string ,, i found two spaces and one space in the blob field
as you mentioned
firstly i replaced 2 spaces with 1 space
secondly replaced 1 space with +

B4X:
           ImageData = colroot.Get("category_pic")
                    
                    ImageData=ImageData.Replace("  "," ")
                    ImageData=ImageData.Replace(" ","+")
 

lazreg

Active Member
Licensed User
i use this code to replace spaces
B4X:
ImageData=ImageData.Replace(" ","+")
and i got this :

B4X:
iVBORw0KGgoAAAANSUhEUgAAApUAAAIsCAIAAAAs9sVNAAAAA3NCSVQICAjb4U/gAAAgAElEQVR4nFy9PY+1SZAsFJHVo7WwsPhNOFiYSEj35+LgISEEErgI4W6fisCIyDo9zN67O/O+3ec8T1VWZkTkR1HS//I//0//7//zf2PG9oCiKduGAQIQANi2AQCGbAIwLcOwYVsiCXvo/KygAW3ZBkzAAKx+iEEaIGmZw/ytSUqegZ2vF3ls5VFsEyAJ2KBtMr+HAQEAFDwQQJiERBgmCIA2METeLT9ugDBAM39h5BucRyUIwgZpYQ5tI08MeB+GGDC/BhMGhgQOoDwXSZIAMF3Rfk3/DTBISN4/tJkVQh+W7z36J+wD9Cn7h6T7Dnnq/YrvP85TWM6bAYZteOzbBTL+fKfxgQewgYFpmGQ3qEZiUwMa0+WA8wAgaQgmZHMOnU/Kk8qcLMh0A0FQFgAja5tHMwjcbJfpfRPaImm4G20b7BLHivx2hYrp2J7hbh8om0NLBE3RU7PK5ptdXu6CdXPA7KbfRg2Y1YydfVeoVjcDCxzGgAHywNfk7t/Yl6DBAUQBB7ocGMQ15sAGRRICDvmvTe+3DQEOgBlb5DBnlqMc1azvMHuX5ct+99/X1GLUMHetYe3K5ecZJzBZZSvbn8POnrU6D4Kmfe3hntJuJvbk5csOYOPOUHc4AwhrzMx5HPIKJDh0Tg7/PHqMtzaV1xvAEDByDaLfzJj2Puv+5gGF/a+6ij+nNgcBA9sUAXBggrI9M7HfGT7fQgJDA8cUzGFPkt55zgNPfAUFjNdPxbbjLLqvWdD8imNZ3QxqL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ert
Licensed User
$category_pic= mysql_real_escape_string($_POST["cateory_pic"]);
Looking around on the web, it looks like you have something called magic quotes enabled (this is a guess from my quick and dirty research). So
1) Disable magic quotes
2) Change the above code to
B4X:
$category_pic= mysql_real_escape_string(stripslashes($_POST["cateory_pic"]))
Without this modification, you are actually saving garbled data. mysql_real_escape_string without magic quotes makes the string supposedly save for MySQL. When you insert the string into MySQL, the escaping is undone and the unaltered data is stored in MySQL. With magic quotes on, you are actually escaping the magic quoted text and MySQL stores the magic quoted text instead of the unaltered string.

Sources:
https://www.webdeveloper.com/forum/...verse-the-effects-of-mysql-real-escape-string
https://stackoverflow.com/questions...pslashes-and-mysql-real-escape-string-togethe
https://phpdelusions.net/delusion/mysql_real_escape_string
 

lazreg

Active Member
Licensed User
Hi @OliverA
i changed the above code and still got error ..
i read all your help in other threads but still i got the same error ..

here is my code to save the picture in mysql db
B4X:
Dim su As StringUtils
    Dim FileBuffer(0) As Byte
    Dim Out As OutputStream
    Out.InitializeToBytesArray(0)
   
    Dim xBitmap As Bitmap
    xBitmap.Initialize3(Module.viewAsBitmap( imgCategory))
    xBitmap.WriteToStream(Out,100,"JPEG")'PNG
    FileBuffer=Out.ToBytesArray
    Out.Close
    Dim B64String As String
    B64String=su.EncodeBase64(FileBuffer)
    Log("imgData before Insert=" & B64String)
    Http.Initialize("InsertCategory", Me)
    Http.PostString("https://www.xxxxx.com/newCategory.php", "Category="&Module.SQLiteEscape(txtCategoryName.EditText.Text.Trim)&"&"&"cateory_pic=" & B64String)
    Http.GetRequest.Timeout = 45000
''    Http.GetRequest.SetHeader("Content-Type", "application/json")
''    Http.GetRequest.SetContentType("application/json")
''    Http.GetRequest.SetContentEncoding("UTF-8")
and my php code to save the category:

B4X:
include ("db.php");

$con = mysql_connect($host,$user,$pw) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES 'utf8'");


        $Category = mysql_real_escape_string($_POST["Category"]);
        $category_pic= $_POST["cateory_pic"];  //mysql_real_escape_string()
        //$category_pic= mysql_real_escape_string(stripslashes($_POST["cateory_pic"]))
        //echo $category_pic ;
        $q = mysql_query("SELECT * FROM categories WHERE category_name = '$Category'");
        $count = mysql_num_rows($q);
        //print json_encode ($count);
        if ($count == 0)
            {
              $res = mysql_query("INSERT INTO categories (category_name,category_pic,deleted) VALUES ('$Category','$category_pic','0')");
            print json_encode ("Inserted");
            }
        else
        {
            print json_encode ("Duplicated");
        }
mysql_close($con);
to retrieve picture from db in PHP i use this code:
B4X:
<?php

include ("db.php");

$con = mysql_connect($host,$user,$pw) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES 'utf8'");

$q = "SELECT category_id,category_name,category_pic FROM categories where deleted = '0' order by category_name ASC";
            $res1 = mysql_query($q);
         if (mysql_errno()) {
            header("HTTP/1.1 500 Internal Server Error");
            // echo $query.'\n';
            echo $res1.'\n';
            echo mysql_error();
        }
        else
        {
            $rows2 = array();
            while($rr = mysql_fetch_assoc($res1))
            //
                {
                if (array_key_exists('category_pic', $rr)) {
                $rr['category_pic'] = base64_encode($rr['category_pic']);
                }
            $rows2[] = $rr;
            }
           
            print json_encode($rows2);
            mysql_free_result($res1);
        }
mysql_close($con);
?>
and my b4a code to display the picture

B4X:
Sub JobDone (Job As HttpJob)
    ProgressDialogHide
    If Job.Success Then
        Dim res As String, action As String
        res = Job.GetString
        Log("Back from Job:" & Job.JobName  & ", Success = " & Job.Success)
        Log("Response from server: " & res)

        Dim parser As JSONParser
        parser.Initialize(res)
   
        Select Job.JobName
            Case "DispCategory"
                '///////////////////////////////
                LV.Clear
                Dim categories As List
                categories = parser.NextArray 'returns a list with maps
               
                SV.Panel.Height= categories.Size * 75dip  +715dip 'LV.Height+1000dip
                LV.Height=  SV.Panel.Height' 300%y 'rs.RowCount * 75dip +300dip
                   
            For Each colroot As Map In categories
                   
                    Dim category_name As String = colroot.Get("category_name")
                    Log("category_name : " & category_name)
                    Dim category_id As String = colroot.Get("category_id")
                    Log("category_id : " & category_id)
                   
                    Log("category_pic :" & colroot.Get("category_pic"))
               
'                  
            Try
    If colroot.Get("category_pic") <> Null  Then
               
                    Log("category_pic :" & colroot.Get("category_pic"))
                       
                        Dim InStream As InputStream
                        Dim B64String As String
                        Dim FileBytes() As Byte
                        Dim su As StringUtils
                        Dim Bitmap1 As Bitmap
                       
                       
                        B64String=colroot.Get("category_pic")
                        FileBytes=su.DecodeBase64(B64String)
                        InStream.InitializeFromBytesArray(FileBytes, 0, FileBytes.Length)
                        Bitmap1.Initialize2(InStream)
                        InStream.Close
                        ''Meal_Pic.SetBackgroundImage(Bitmap1)
                        LV.AddTwoLinesAndBitmap2(category_name,category_id,Bitmap1,category_id)
                       
                    Else
                        Dim ximg As Bitmap
                        ximg = LoadBitmap(File.DirAssets, "noimg.png")
                        LV.AddTwoLinesAndBitmap2(category_name,category_id,ximg,category_id)
                    End If
            Catch
                        ToastMessageShow("Error", True)
                        Log(LastException)
            End Try
            Next
                   
               
'                '////////////////////////////////
        End Select
    Else
        Log("Job.Success: " & Job.Success)
        Log("Error: " & Job.ErrorMessage)
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub
that's all
i try a lot of codes but no way
i guess the problem from the content type of the image when saving it ..
i read this thread
https://www.b4x.com/android/forum/threads/string-to-bitmap.13116/#post-191524
and my question is how to add this content
B4X:
 Dim Logo = "data:image/png;base64,"
 

OliverA

Expert
Licensed User
$rr['category_pic'] = base64_encode($rr['category_pic']);
Don't do this. You are already storing a Base64 encoded string in your DB. That code looks familiar. It is used if you store the image in binary format in the DB. Everything in my previous post about magic quotes is most likely hogwash (see signature).
 

lazreg

Active Member
Licensed User
as Erel said
after more than 14 hours i got it ,, i used this code when retrieving image and before decoding string
B64String=B64String.Replace(" ","++")
B64String=B64String.Replace(" ","+")
but i replace every 2spaces with ++
and every space with +

now it works perfectly..
thanks @OliverA for your help..
 
Top