将图像保存为字符串(将图像转换为字符串) [英] Saving image as a string (converting image to string)

查看:117
本文介绍了将图像保存为字符串(将图像转换为字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在保存按钮中使用此代码,以使用c#winforms在sql server中的文本数据类型中将图像作为字符串插入。下面的代码将图像转换为字符串,但我不知道如何在保存/插入时使用它。任何帮助将不胜感激。谢谢!



我的尝试:



How to use this code in a save button for inserting image as a string in a text data type in sql server using c# winforms. The code below converts an image to string but I don't know how to use it in saving/inserting. Any help will be appreciated. Thank you!

What I have tried:

public string ImageToBase64(Image image, 
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

推荐答案

不要将数据存储在数据库中的Base64中 - 效率非常低且图像效果不佳大到足以开始存储它们通常是一个坏主意。少量缩略图(或拇指大小的图像)确定 - 但全尺寸图像或大量图像,您开始大幅减慢一切。更好的想法是使用BLOB / IMAGE / VARBINARY列将它们存储在二进制文件中,或者甚至更好地存储数据库中文件的路径,并根据需要访问该文件中的图像。



插入二进制数据很简单 - 只要您使用参数化查询,无论如何都应该这样做 - 您可以在这里找到代码:为什么我得到参数无效。我从数据库中读取图像时出现异常? [ ^ ]
Don't store images in Base64 in your DB - it's very inefficient and images are big enough to start with that it's often a bad idea to store them at all. Small numbers of Thumbnails (or thumb sized images) OK - but full sized images or large quantities and you start to slow everything down dramatically. A better idea is to store them in binary using a BLOB / IMAGE / VARBINARY column, or even better store a path to the file in the DB, and access the image that from that as necessary.

Inserting binary data is simple - provided you use parameterized queries which should always do anyway - you'll find the code here: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^]


Google是你的朋友。 [ ^ ]


这篇关于将图像保存为字符串(将图像转换为字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆