简体   繁体   English

将 Image 数据类型转换为 Base64,将 Base64 转换为 Image 数据类型

[英]Convert Image data type into Base64 and Base64 into Image data type

I'm using Data-Type "Image" in MS SQL 2012 to store Image.我在 MS SQL 2012 中使用数据类型“图像”来存储图像。

problem: I have an image in BASE64 string in C#问题:我在 C# 中的 BASE64 字符串中有一个图像

/9j/4AAQSkZJRgABAQEASABIAAD/4SKhRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUAAAABAAAAYgEbAAUAAAABAAAAagEoAAMAAAABAAIAAAExAAIAAAAeAAAAcgEyAAIAAAAUAAAAkIdpAAQAAAABAAAApAAAANAALcbAAAAnEAAtxsAAACcQQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykAMjAxNjowMjowNSAxNDo1MTo0MwAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAFUKADAAQAAAABAAACWAAAAAAAAAAGAQMAAwAAAAEABgAAARoABQAAAAEAAAEeARsABQAAAAEAAAEmASgAAwAAAAEAAgAAAgEABAAAAAEAAAEuAgIABAAAAAEAACFrAAAAAAAAAEgAAAABAAAASAAAAAH/2

I am converting it into byte[] in C# as I need to save it into a column of data type IMAGE.我将它转换为 C# 中的 byte[],因为我需要将它保存到数据类型为 IMAGE 的列中。 Like this:像这样:

byte[] imageInByteArray =Convert.FromBase64String("MyImage");

It is saved successfully like this:保存成功如下:

The byte[] array data in database -数据库中的 byte[] 数组数据 -

在此处输入图片说明

Now I am trying to retrieve an image and converting it back into BASE64 using this:现在我正在尝试使用以下方法检索图像并将其转换回 BASE64:

var imageA = results.Read<byte[]>().ToArray();
string imageB =Convert.ToBase64String(imageA);

Now I am getting the result like this:现在我得到这样的结果:

MHhGRkQ4RkZFMTAwNTg0NTc4Njk2NjAwMDA0RDREMDAyQTAwMDAwMDA4MDAwNDg3NjkwMDA0MDAwMDAwMDEwMDAwMDAzRTAxMTIw

The result is not what I was expecting it should be like this结果不是我所期望的它应该是这样的

/9j/4AAQSkZJRgABAQEASABIAAD/4SKhRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUAAAABAAAAYgEbAAUAAAABAAAAagEoAAMAAAABAAIAAAExAAIAAAAeAAAAcgEyAAIAAAAUAAAAkIdpAAQAAAABAAAApAAAANAALcbAAAAnEAAtxsAAACcQQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykAMjAxNjowMjowNSAxNDo1MTo0MwAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAFUKADAAQAAAABAAACWAAAAAAAAAAGAQMAAwAAAAEABgAAARoABQAAAAEAAAEeARsABQAAAAEAAAEmASgAAwAAAAEAAgAAAgEABAAAAAEAAAEuAgIABAAAAAEAACFrAAAAAAAAAEgAAAABAAAASAAAAAH/2

I found the solution for this, Please look into this because it might be useful when you do not want to change your datatype Image in your database:我找到了解决方案,请查看此问题,因为当您不想更改数据库中的数据类型 Image 时,它​​可能很有用:

I sent base64 string as it is to database and there I converted it into varbinary like this:我将 base64 字符串按原样发送到数据库,然后在那里将其转换为 varbinary,如下所示:

SELECT CAST(N'' AS xml).value('xs:base64Binary(sql:variable("@Image2"))', 'varbinary(max)')

and inserted it into the image column.并将其插入到图像列中。

then I retrieved an image in base64 like this:然后我在 base64 中检索了一个图像,如下所示:

 SELECT cast('' as xml).value('xs:base64Binary(sql:column("img"))', 'varchar(max)') FROM imageTemp WHERE...

It gave me the exact Base64 string which I have sent earlier.它给了我之前发送的确切 Base64 字符串。

Thank You.谢谢你。

I believe you need help on how to store image data in sql server.我相信您需要有关如何在 sql server 中存储图像数据的帮助。

You can create a table like below.您可以创建如下表。 Please note that you may not want to create database , just a table would suffice.请注意,您可能不想创建数据库,一个表就足够了。 If you already have a table where you want to save this data, you will have to make sure that the type of column is varbinary(max).如果您已经有一个要保存此数据的表,则必须确保列的类型为 varbinary(max)。

CREATE DATABASE MyDatabase;  
GO  
USE MyDatabase;  
GO  
CREATE TABLE MyImageDatabaseTable (Id int, BLOBData varbinary(max));  
GO  

Then you can read the data as:然后您可以将数据读取为:

SqlConnection objConn = new SqlConnection(connectionString);  
objConn.Open();  
SqlCommand objCmd = new SqlCommand("Select * From MyImageDatabaseTable", objConn);  
SqlDataReader dr = objCmd.ExecuteReader();  
while(dr.Read())
{
     byte[] myImageByteArrayData = (byte[]) dr["BLOBData"];  

     string myImageBase64StringData = Convert.ToBase64String(myImageByteArrayData );
}

Hope this helps.希望这可以帮助。

Answering your question回答你的问题

How to retrieve base64 from database using this byte[] array?如何使用这个 byte[] 数组从数据库中检索 base64?

SQL-Server will transform your binary to base64 implicitly when embedding it into XML.将二进制文件嵌入到 XML 中时,SQL-Server 会将其隐式转换为 base64。

Try this尝试这个

--I fill a binary variable with some dummy content
DECLARE @SomeBinary VARBINARY(MAX) = CAST('This is a dummy content' AS VARBINARY(MAX));
--this is the resulting binary
SELECT @SomeBinary;
--Now you see what happens using FOR XML PATH
SELECT (SELECT @SomeBinary FOR XML PATH(''))

We can re-convert this easily我们可以轻松地重新转换

DECLARE @base64 VARCHAR(MAX)='VGhpcyBpcyBhIGR1bW15IGNvbnRlbnQ=';
SELECT CAST(@base64  AS XML).value('.','varbinary(max)');

Probably you'll have to use a CAST(YourImageTypedColumn AS VARBINARY(MAX)) first.可能您必须首先使用CAST(YourImageTypedColumn AS VARBINARY(MAX))

But it might be easier to retrieve this as binary and to the conversion on your client side application.但是,将其作为二进制文件检索并在客户端应用程序上进行转换可能更容易。

I use this method bellow, to convert bytearray from database to an image.我在下面使用这种方法,将 bytearray 从数据库转换为图像。

public Bitmap ConvertByteArrayToBitmap(byte[] Array)
{
    if (Array == null) return null;

    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        ms.Write(Array, 0, Array.Length);
        ms.Position = 0L;

        return new Bitmap(ms);
    }
}

Regards.问候。

You can Convert binary to Base64 using XML and the hint "for xml path"您可以使用 XML 和“for xml path”提示将二进制文件转换为 Base64

select file_name,ColumnWithBinary,ColumnToSwFinalResult
from TableWithBinary
cross apply (select ColumnWithBinary '*' for xml path('')) T (ColumnToSwFinalResult)
GO

在此处输入图片说明

I got it!!!我知道了!!!

C# code C# 代码

string base64Encoded = Convert.ToBase64String(((byte[])result.photoFromSQLImageColumn));
string base64Decoded;
byte[] data = System.Convert.FromBase64String(base64Encoded);
base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data);

and in this variable -----> base64Decoded you will have your rigth base64 string!!在这个变量 -----> base64Decoded 中,您将拥有正确的 base64 字符串!!

Greetings from México!!!来自墨西哥的问候!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM