Friday, February 28, 2014

asp.net mvc c# upload image, generate and upload thumbnail

public void UploadProductImage(HttpPostedFileBase file)
        {
            string subPath = "~/Images/";

            bool isExists = System.IO.Directory.Exists(Server.MapPath(subPath));

            if (!isExists)
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
            }

            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(Server.MapPath(subPath), pic);

                file.SaveAs(path);

                UploadProductImageThumbnail(file, productId);
            }
        }


public void UploadProductImageThumbnail(HttpPostedFileBase file)
        {
            using (var image = Image.FromStream(file.InputStream, true, true))
            {
                var thumbWidth = 50;
                var thumbHeight = 50;

                using (var thumb = image.GetThumbnailImage(
                    thumbWidth,
                    thumbHeight,
                    () => false,
                    IntPtr.Zero))
                {
                    var jpgInfo = ImageCodecInfo.GetImageEncoders()
                        .Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();

                    using (var encParams = new EncoderParameters(1))
                    {
                        string thumbPath = "~/Images/Thumbnails";
                        bool isExists = System.IO.Directory.Exists(Server.MapPath(thumbPath));

                        if (!isExists)
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath(thumbPath));
                        }

                        var thumbPathFull = Path.Combine(Server.MapPath(thumbPath), file.FileName);
                        long quality = 100;
                        encParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
                        thumb.Save(thumbPathFull, jpgInfo, encParams);
                    }
                }
            }
        }

Friday, February 21, 2014

linq compare int with string

products = products.Where(p =>
                    SqlFunctions.StringConvert((double)p.ProductId).Trim() == searchString);