Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Convert image field to Base64

Author  Topic 

fralo
Posting Yak Master

161 Posts

Posted - 2011-10-27 : 09:35:40
Hi all,

Do you know if it's possible to convert an image field to base64binary format using sql. I have some code which queries a table and then writes it to an xml file. I need to include a base64 represenation of the image in the output. Here's my query. The image field is named 'inmpicture'. There's no simple CONVERT command, is there?

SELECT inmpicture as FrontalPortrait, ltrim(rtrim(a.race)) as Race, ltrim(rtrim(a.height)) as Height,ltrim(rtrim(a.lname)) as Lastname,ltrim(rtrim(a.fname)) as Firstname,ltrim(rtrim(a.sex)) as Gender,ltrim(rtrim(a.dob)) as Dob, FROM jail.dbo.jailbook a, where a.lname is not null");

Lumbago
Norsk Yak Master

3271 Posts

Posted - 2011-10-27 : 10:26:45
Seems like these functions will do it for you (haven't tested them though):

http://www.vbforums.com/showthread.php?t=554886

- Lumbago
My blog-> http://thefirstsql.com/2011/07/08/how-to-find-gaps-in-identity-columns-at-the-speed-of-light/
Go to Top of Page

paultech
Yak Posting Veteran

79 Posts

Posted - 2011-10-27 : 10:44:01
Ok Man try the code below
Below is a sample that calls this UDF with chunks of 2400 characters (because of the way Base64 encoding works, the “chunk” size has to be divisible by 4).

CREATE PROCEDURE testConvert
@someParameter int,
@attachmentData text
AS

/*** Table schema used for test
CREATE TABLE testData(someValue int, attachmentData image, CONSTRAINT PK_testData primary key nonclustered (someValue))
***/

-- insert NULL (0x0) into the image field so that the TEXTPTR function will work
insert testData(someValue, attachmentData)
values(@someParameter, 0x0)

declare @pointer varbinary(16)
select @pointer = TEXTPTR(attachmentData) from testData where someValue = @someParameter

declare @buff varchar(2400)
declare @offset int, @imgOffset int
set @offset = 1
set @imgOffset = 0
while @offset <= datalength(@attachmentData)
begin
select @buff = substring(@attachmentData, @offset, 2400)
declare @img varbinary(8000)
select @img = dbo.base64toBin(@buff)
UPDATETEXT testData.attachmentData @pointer @imgOffset NULL @img
set @imgOffset = @imgOffset + datalength(@img)
set @offset = @offset + 2400
end


to read the full orginal article you can go to
http://geekswithblogs.net/scarpenter/archive/2005/10/19/57442.aspx

paul Tech
Go to Top of Page
   

- Advertisement -