iPhone to MS SQL Image Data Type Conversion Questi

2019-08-30 09:48发布

Alright, here we go!

I am currently developing an iPhone app that will work as a security check-in system for events at a church. The main goal is to be able to search a pre existing MS SQL database for a participant, and then save them to a list on the iPhone/iPod Touch/iPad. Easy enough. One of the fields in the MS SQL database is of Image data type, and its function is to store the participant's image in binary form. I currently am not allowed to switch to varbinary(MAX).

From the iPhone, I use:

UIImage *image = [UIImage imageNamed:@"nameOfImage.jpg"];  
NSData *imageData = UIImageJPEGRepresentation(image,1.0);  
NSString *imageString = (NSString *)[[[NSString alloc] init] base64StringFromData:(NSData *)imageData];

You may be wondering what the base64StringFromData is. It's a category discussed here, How do I do base64 encoding on iphone-sdk?

In the category, it returns a string as NSASCIIStringEncoding. I then send that string to a Visual Basic web service using POST.

Assume in the following that I have already set up and opened my SQL connection, and initlialized a SQL Data adapter and command. So the function looks similar to this:

Public Function sendCommand(ByVal image As String) As String
   Dim commandString As String
   commandString = "insert into phoneApp(image) values(@image)"

   Dim encoding As New System.Text.UTF8Encoding

   sqlDataAdapter.InsertCommand = (commandString, sqlConnection)
   sqlDataAdapter.InsertCommand.Parameters.Add(@"image", SqlDbType.Image, image.length).Value = encoding.GetBytes(image)
   sqlDataAdapter.ExecuteNonQuery()
End Function

Now, finally, here's what is happening. In another function, I call Response.BinaryWrite(SqlDataReader.Item("image")). In Internet Explorer, doing this would then make the image appear in the browser. Instead, it displays the string in base64 form. Copy and pasting that string in a base64 converter off the net, and it works. So the encoding on the iPhone did encode to base64 properly.

Here's the question. Do I even need to be encoding to base64 to save into Image Data Type, or should I be focusing on learning how to encode the NSData into a different binary string?

1条回答
迷人小祖宗
2楼-- · 2019-08-30 09:57

I figured it out, and will leave my answer to anyone that stumbles across this. Good luck to you in your programming.

It actually was a lot simpler than I thought. Just use System.Convert to pass in the bytes on the InsertCommand.

   sqlDataAdapter.InsertCommand = (commandString, sqlConnection)
   sqlDataAdapter.InsertCommand.Parameters.Add(@"image", SqlDbType.Image, image.length).Value = System.Convert.FromBase64String(image)
   sqlDataAdapter.ExecuteNonQuery()

In essence, I was getting the bytes for the encoding string but never decoding it further down the line. So I stopped the double encoding by using the Convert before it was inserted into the table.

查看更多
登录 后发表回答