查询返回的 varbinary 字符串比实际字符串短。

huangapple go评论76阅读模式
英文:

Query returns shorter varbinary string than the actual string

问题

其中一个表存储长的VARBINARY(MAX)字符串来表示图像。

我尝试选择图像并将它们转换回图像。

我注意到结果显示一个较短的字符串:

$data = DB::select("
SELECT photo_string
FROM users_photos
WHERE user_id = 123
");

echo(strlen($data[0]->photo_string)); // 显示 26633

但当我从表中复制字符串并对其执行strlen()时,它是53268

这个字符串看起来像 0xFFD8FFE0......

为什么?

英文:

One of the tables stores long VARBINARY(MAX) strings to represent images.

I am trying to select images and convert them to back to images.

I noticed that the result shows a much shorter string:

$data = DB::select("
SELECT photo_string
FROM users_photos
WHERE user_id = 123
");

echo(strlen($data[0]->photo_string)); // shows 26633

But when I copy the string from the table and do strlen() on itm it's 53268

The string looks like 0xFFD8FFE0......

Why?

答案1

得分: 2

你正在经历的行为可能是由图像数据在数据库中存储和通过查询检索的方式引起的。当将图像存储为VARBINARY(MAX)字符串时,图像的实际二进制数据会被转换成一系列字节,并表示为字符的字符串。

当您使用查询检索图像数据时,数据库可能会返回二进制数据的编码表示,而不是实际的二进制数据本身。这可能导致字符串长度较原始二进制数据较短。

要将检索到的字符串转换回图像,您需要反向编码过程并将其转换回其原始的二进制格式。具体的方法取决于所使用的编码机制。将图像存储为字符串的常见编码机制包括Base64编码。

你可以尝试这样做:

$data = DB::select("
    SELECT photo_string
    FROM users_photos
    WHERE user_id = 123
");

$encodedString = $data[0]->photo_string;
$decodedData = base64_decode($encodedString);
英文:

The behavior you're experiencing is likely due to the way the image data is stored in the database and retrieved through your query. When storing images as VARBINARY(MAX) strings, the actual binary data of the image is converted into a series of bytes and represented as a string of characters.

When you retrieve the image data using your query, the database may be returning the encoded representation of the binary data rather than the actual binary data itself. This can result in a shorter string length compared to the original binary data.

To convert the retrieved string back into an image, you need to reverse the encoding process and convert it back into its original binary format. The specific method to accomplish this depends on the encoding mechanism used. Common encoding mechanisms for storing images as strings include Base64 encoding.

you can try this:

$data = DB::select("
    SELECT photo_string
    FROM users_photos
    WHERE user_id = 123
");

$encodedString = $data[0]->photo_string;
$decodedData = base64_decode($encodedString);

huangapple
  • 本文由 发表于 2023年6月27日 17:54:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定