ASP.NET: C# – How to scale image and save to DB?

DB design

Create table IMAGE to save image

[sql]
sample_image varbinary(MAX)
[/sql]

Create SP to save image

[sql]
CREATE PROCEDURE [insert_image]
@input varbinary(MAX),
@length bigint
@auto bigint=null OUTPUT
AS
INSERT IMAGE(
sample_image,
image_length
)
VALUES(
@input,
@length,
)

SET @auto = @@identity
[/sql]

Create function to save/ scale image

[js]
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpPostedFile hpfFile = fupSampleAttachment.PostedFile;
int size = hpfFile.ContentLength;
var input = new byte[size];

Bitmap Postedfile = new Bitmap(hpfFile.InputStream);
System.Drawing.Image img = ScaleImage(Postedfile, 2000, 2000);
input = imageToByteArray(img);

Stream iStream = hpfFile.InputStream;

// Read the file into the byte array.
iStream.Read(input, 0, size);
strFileName = hpfFile.FileName.Substring(hpfFile.FileName.LastIndexOf(@”\”) + 1);
string strTimeStamp = DateTime.Now.ToString(“ddMMyyhhmmss”);

try
{
if (hpfFile != null && hpfFile.FileName != string.Empty && hpfFile.ContentLength >= 1)
{
bool blnSuccess = true;
blnSuccess = InsertImageToDB(input);
}
}
catch (Exception upEx)
{
string strUpEx = upEx.Message;
}
finally
{
}
}

public static bool insertImage(byte[] input, int length)
{
bool returnValue = false;
DBase db = new DBase();

SqlParameter[] prmImage = new SqlParameter[1];

prmImage[1] = new SqlParameter(“@input”, SqlDbType.VarBinary, input.Length);
prmImage[1].Value = input;

try
{
db.ExecuteNonQuery(“insert_image”, prmImage);
return true;
}
catch { }

return false;
}

public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight)
{
if (image.Width <= maxWidth && image.Height <= maxHeight) return image; var ratioX = (double)maxWidth / image.Width; var ratioY = (double)maxHeight / image.Height; var ratio = Math.Min(ratioX, ratioY); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); var newImage = new Bitmap(newWidth, newHeight); using (var graphics = Graphics.FromImage(newImage)) graphics.DrawImage(image, 0, 0, newWidth, newHeight); return newImage; } public byte[] imageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; return ms.ToArray(); } [/js]

How to validate upload file extension

[js]






[/js]

Be the first to comment

Leave a Reply

Your email address will not be published.


*