方式进行当读范亦亦亦作预目预 [英] C# Resize jpg image, convert to byte and save into database using varbinary

查看:190
本文介绍了方式进行当读范亦亦亦作预目预的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调整使用FileUpload控件上传的jpg图像的大小,并将其转换为字节,然后将其保存为数据库(SQL Server 2008)(varbinary(MAX))。我所做的和代码如下所示是我设法将其转换为字节并以varbinary(MAX)形式保存到数据库中。我想知道如何在做所有这些功能之前调整图像的大小。帮助我

读取文件

$ p $ string $ filePath = FileUpload1.PostedFile 。文件名;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);

根据文件扩展名设置contenttype

  string contenttype = String.Empty; 
switch(ext)
{
case.jpg:
contenttype =image / jpg;
break;





使用varbinary转换为字节并保存到数据库中

  if(contenttype!= String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;

BinaryReader br = new BinaryReader(fs);

Byte [] bytes = br.ReadBytes((Int32)fs.Length);

//将文件插入数据库
string strQuery =insert into MemberReport(username,typeofcrime,location,crdatetime,citizenreport,image1,image2,image3,image4,image5)+ $ ()+ detail.Trim()返回一个值为'b + b'的值(''+ username +'','+ typeofcrime +','+ location.Trim()+','+ datetime + +',@Data,@ Data2,@ Data3,@ Data4,@ Data5);
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add(@ Data,SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add(@ Data2,SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add(@ Data3,SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add(@ Data4,SqlDbType.Binary).Value = bytes4;
cmd.Parameters.Add(@ Data5,SqlDbType.Binary).Value = bytes5;
InsertUpdateData(cmd);

lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text =发送报告!;

}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text =文件格式无法识别。 +
上传图片格式;



$ b InsertUpdateData方法

 cmd.CommandType = CommandType.Text; 
cmd.Connection = con;
尝试
{
con.Open();
cmd.ExecuteNonQuery();
返回true;

catch(Exception ex)
{
Response.Write(ex.Message);
返回false;
}
finally
{
con.Close();
con.Dispose();


解决方案

文件添加到 Image 对象,可以简单地使用:

 上传的图片= Image.FromStream(FileUpload1.PostedFile.InputStream); 

接下来,弄清楚图像有多大。假设您想要最大尺寸为256像素,并保持宽高比。一些代码改编自CodeProject文章调整大小使用.NET即时影像

  int originalWidth = uploaded.Width; 
int originalHeight = uploaded.Height;
float percentWidth =(float)256 /(float)originalWidth;
float percentHeight =(float)256 /(float)originalHeight;
float percent = percentHeight< percentWidth? percentHeight:percentWidth;
int newWidth =(int)(originalWidth * percent);
int newHeight =(int)(originalHeight * percent);

现在创建一个新的位图对象来包含(图片来自同一个CodeProject文章),并将原始图像绘制到它:

  Image newImage = new Bitmap(newWidth, newHeight); 
using(Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(上传,0,0,newWidth,newHeight);





最后,转换回字节保存到数据库中:

  byte []结果; 
using(MemoryStream ms = new MemoryStream())
{
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()。FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
EncoderParameters jpegParms = new EncoderParameters(1);
jpegParms.Param [0] = new EncoderParameter(Encoder.Quality,95L);
newImage.Save(ms,codec,jpegParms);
results = ms.ToArray();
}

我花了很长的路线设置输出的质量等级。如果你不介意使用什么压缩级别,一个简单的 img.Save(ms,ImageFormat.Jpeg); 调用会替换使用代码块。



查看 CodeProject文章我上面提到的更多信息调整图像,并阅读 / b>(同样在CodeProject上)更多地将图像转换成字节数组。/ b>




最后一部分,将图像插入到数据库表中。我将假定Microsoft SQL,并执行一个非常简单的表插入。

表被定义为:

<$ p ($ 1,1)$ NULL $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED

[ID] ASC
)WITH(PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

将图像数据插入到表中:

pre $ static $ connString =Data Source = localhost; Initial Catalog = project; Integrated Security =真正;
$ b使用(SqlConnection conn =新的SqlConnection(connString))
{
conn.Open() ();

(SqlCommand cmd = new SqlCommand(INSERT INTO Images(ImageData)OUTPUT inserted.ID VALUES(@ p1),conn))
{
cmd.Parameters。 AddWithValue(@ p1,imgdata);

int res =(int)cmd.ExecuteScalar()
return res;





返回的值是auto



或更新现有图片:

 使用(SqlConnection conn = new SqlConnection(connString))
{
conn。打开();
using(SqlCommand cmd = new SqlCommand(UPDATE Images SET ImageData = @ p1 WHERE ID = @ p2,conn))
{
cmd.Parameters.AddWithValue(@ p1, imgdata);
cmd.Parameters.AddWithValue(@ p2,id);

cmd.ExecuteNonQuery();
}
}
}


I'm trying to resize my jpg image uploaded by using FileUpload control and convert it into byte before saving it to database (SQL Server 2008) as (varbinary(MAX)). What I have done and code show below was that I manage to convert it into byte and save into database as varbinary(MAX). I wish to know how to I resize the image before doing all those function. Do help me out. Thanks!

Read the file

string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);

Set the contenttype based on File Extension

string contenttype = String.Empty;            
switch (ext)
{
   case ".jpg":
   contenttype = "image/jpg";
   break;
}

Convert into byte and save into database using varbinary

if (contenttype != String.Empty)
{
            Stream fs = FileUpload1.PostedFile.InputStream;

            BinaryReader br = new BinaryReader(fs);

            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            //insert the file into database
            string strQuery = "insert into MemberReport(username, typeofcrime, location, crdatetime, citizenreport, image1, image2, image3, image4, image5)" +
               " values ('" + username + "','" + typeofcrime + "','" + location.Trim() + "','" + datetime + "','" + detail.Trim() + "', @Data, @Data2, @Data3, @Data4, @Data5)";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
            cmd.Parameters.Add("@Data2", SqlDbType.Binary).Value = bytes2;
            cmd.Parameters.Add("@Data3", SqlDbType.Binary).Value = bytes3;
            cmd.Parameters.Add("@Data4", SqlDbType.Binary).Value = bytes4;
            cmd.Parameters.Add("@Data5", SqlDbType.Binary).Value = bytes5;
            InsertUpdateData(cmd);

            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "Report Sent!";

        }
        else
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "File format not recognised." +
              " Upload Image formats";
        }

InsertUpdateData method

    private Boolean InsertUpdateData(SqlCommand cmd)
    {
        SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            return false;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }

解决方案

You need to convert the uploaded file to an Image object, which can be done simply with:

Image uploaded = Image.FromStream(FileUpload1.PostedFile.InputStream);

Next, figure out how big you want the image to be. Let's say you want the largest dimension to be 256 pixels, and maintain aspect ratio. Some code adapted from the CodeProject article Resizing an Image On-The-Fly using .NET:

int originalWidth = uploaded.Width;
int originalHeight = uploaded.Height;
float percentWidth = (float)256 / (float)originalWidth;
float percentHeight = (float)256 / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
int newWidth = (int)(originalWidth * percent);
int newHeight = (int)(originalHeight * percent);

Now create a new Bitmap object to contain the resized image (from the same CodeProject article) and draw the original image to it:

Image newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(uploaded, 0, 0, newWidth, newHeight);
}

And finally, convert back to bytes to save into the database:

byte[] results;
using (MemoryStream ms = new MemoryStream())
{
    ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
    EncoderParameters jpegParms = new EncoderParameters(1);
    jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
    newImage.Save(ms, codec, jpegParms);
    results = ms.ToArray();
}

I took the long route to set the quality level of the output. If you don't mind what compression level is used, a simple img.Save(ms, ImageFormat.Jpeg); call replaces the first 4 lines inside the using code block.

Check out the CodeProject article I mentioned above for more information on resizing images, and read C# Image to Byte Array and Byte Array To Image Converter Class (also on CodeProject) for more on converting images to/from byte arrays.


The last part, inserting the image into a database table. I'll assume Microsoft SQL, and do a very simple table insert.

Table is defined as:

CREATE TABLE [Images](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ImageData] [varbinary](max) NULL,
    CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

And the code to insert the image data into the table:

static string connString = "Data Source=localhost; Initial Catalog=project; Integrated Security=True";

public static int InsertImage(byte[] imgdata)
{
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();

        using (SqlCommand cmd = new SqlCommand("INSERT INTO Images(ImageData) OUTPUT inserted.ID VALUES(@p1)", conn))
        {
            cmd.Parameters.AddWithValue("@p1", imgdata);

            int res = (int)cmd.ExecuteScalar()
            return res;
        }
    }
}

The returned value is the auto-increment value generated by SQL for the record.

Or to update an existing image:

public static void UpdateImage(int id, byte[] imgdata)
{
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("UPDATE Images SET ImageData = @p1 WHERE ID = @p2", conn))
        {
            cmd.Parameters.AddWithValue("@p1", imgdata);
            cmd.Parameters.AddWithValue("@p2", id);

            cmd.ExecuteNonQuery();
        }
    }
}

这篇关于方式进行当读范亦亦亦作预目预的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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