C# Resize jpg image, convert to byte and save into database using varbinary

半城伤御伤魂 提交于 2019-11-30 22:31:01
Corey

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();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!