如何在SQL中将varchar转换为image数据类型?

时间:2018-05-02 17:14:29

标签: sql image type-conversion sql-server-2014 sqldatatypes

我有一个C#Web应用程序,它的工作是将捕获的图像以字节形式发送到数据库,这是SQL中的数据类型图像。这里的问题是网站的DAL不允许我通过它发送字节,即使网络服务不允许我这样做。所以我想弄清楚:如果我将字节转换为普通字符串然后在存储过程中将其转换回数据类型图像并存储它会怎样。这可能吗?

 ALTER PROCEDURE [dbo].[spInsertpic]
    (
        @ID             int , 
        @CapturedPhoto image -- Maybe get this << Data type as NVARCHAR and convert to data typeImage?
    )
AS

if exists (select * from tbpeople where ID=@ID)
    BEGIN
    UPDATE tbPeople 
    SET      
             DateCapturedPhoto = getdate(),
             CapturedPhoto=@CapturedPhoto
    WHERE   ( ID= @ID)

    END 
Else 

    Begin

    INSERT INTO tbPeople        (   
            ID
            , CapturedPhoto
        )
    VALUES
        (   
              @ID 
                        , @CapturedPhoto
        )
END

1 个答案:

答案 0 :(得分:0)

你将不得不跳过几个箍来完成这项工作,但一般的方法是先将图像捕捉到base64字符串。

var encodedImageString = Convert.ToBase64String(imageBytes);

从那里,您可以将字符串传递给存储过程。然后,您必须将其转换回二进制文件。

ALTER PROCEDURE [dbo].[spInsertpic]
(
    @ID INT, 
    @EncodedCapturedPhoto VARCHAR(MAX)
)
AS

DECLARE @CapturedPhoto IMAGE

SET @CapturedPhoto = cast(N'' as xml).value('xs:base64Binary(sql:variable("@EncodedCapturedPhoto"))', 'VARBINARY(4000)');

IF EXISTS (SELECT * FROM tbpeople WHERE ID=@ID)
BEGIN
    UPDATE tbPeople 
    SET      
             DateCapturedPhoto = getdate(),
             CapturedPhoto=@CapturedPhoto
    WHERE   ( ID= @ID)

END 
Else 

    Begin

    INSERT INTO tbPeople        (   
            ID
            , CapturedPhoto
        )
    VALUES
        (   
              @ID 
                        , @CapturedPhoto
        )
END