Inheritance: System.MarshalByRefObject, IDisposable
Example #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="waterImg"></param>
 /// <returns></returns>
 protected Image CreateFillImage(Image waterImg)
 {
     Graphics gType = Graphics.FromImage(waterImg);
     gType.DrawString(Text, TextFont, new SolidBrush(Color.Black), 1, 1);
     gType.DrawString(Text, TextFont, new SolidBrush(Color.White), 0, 0);
     return waterImg;
 }
Example #2
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ConvolutionMatrixManager.Smooth().Apply(img);
     }
 }
 /// <summary>
 /// Constructor of a true false column that creates a column
 /// using, be default, a check mark for true and no image for false values.
 /// </summary>
 /// <param name="field">The field within a dataview to use for the column.</param>
 /// <param name="maxWidth">The maximum width for this column</param>
 public ReportBoolColumn(string field, float maxWidth)
     : base(field, maxWidth)
 {
     Bitmap trueBmp = new Bitmap (GetType(), DefaultTrueImageName);
     trueBmp.MakeTransparent ();
     TrueImage = trueBmp;
 }
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ColorMatrixManager.Contrast(Value).Apply(img);
     }
 }
 protected AojPrintPropertySystem(AojPrintPropertySystem propertySystem)
 {
     lock (new object())
     {
         this._id = propertySystem.Id;
         this._x = propertySystem.X;
         this._y = propertySystem.Y;
         this._realX = propertySystem.RealX;
         this._realY = propertySystem.RealY;
         this._width = propertySystem.Width;
         this._height = propertySystem.Height;
         this._backgroundColor = propertySystem.BackgroundColor;
         this._backgroundShape = propertySystem.BackgroundShape;
         this._backgroundStyle = propertySystem.BackgroundStyle;
         this._borderColor = propertySystem.BorderColor;
         this._borderStyle = propertySystem.BorderStyle;
         this._borderWidth = propertySystem.BorderWidth;
         this._fontColor = propertySystem.FontColor;
         this._fontDisplayFormat = propertySystem.FontDisplayFormat;
         this._fontFamilyName = propertySystem.FontFamilyName;
         this._fontSize = propertySystem.FontSize;
         this._fontStyle = propertySystem.FontStyle;
         this._src = propertySystem.Src;
         this._imgPrint = propertySystem.ImgPrint;
         this._imageMode = propertySystem.ImageMode;
         this._alignment = propertySystem.Alignment;
         this._value = propertySystem.Value;
         this._viewFormat = propertySystem._viewFormat;
     }
 }
Example #6
0
        //    1) Prevent anti-aliasing.
        //...
        //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //// add below line
        //g.CompositingMode = CompositingMode.SourceCopy;
        //...
        //http://stackoverflow.com/questions/4772273/interpolationmode-highqualitybicubic-introducing-artefacts-on-edge-of-resized-im


        ////resize the image to the specified height and width
        //using (var resized = ImageUtilities.ResizeImage(image, 50, 100))
        //{
        //    //save the resized image as a jpeg with a quality of 90
        //    ImageUtilities.SaveJpeg(@"C:\myimage.jpeg", resized, 90);
        //}

        // Sourced from:
        // http://stackoverflow.com/questions/249587/high-quality-image-scaling-c-sharp

        /// <summary>
        /// Resize the image to the specified width and height.
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="size">The width and height to resize to.</param>
        /// <returns>The resized image.</returns>
        public static Bitmap ResizeImage(Image image, Size size)
        {
            if (size.Width < 1 || size.Height < 1)
            {
                return null;
            }

            // a holder for the result
            var result = new Bitmap(size.Width, size.Height);
            //set the resolutions the same to avoid cropping due to resolution differences
            result.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //use a graphics object to draw the resized image into the bitmap
            using (Graphics graphics = Graphics.FromImage(result))
            {
                //set the resize quality modes to high quality
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //draw the image into the target bitmap
                graphics.DrawImage(image, 0, 0, result.Width, result.Height);
            }

            //return the resulting bitmap
            return result;
        }
Example #7
0
        public ScrollBarThumb(ScrollBarThumbDefaults type)
        {
            this._imageAttributes = new ImageAttributes();
            this._imageAttributes.ClearColorKey();
            this._gripImageAttributes = new ImageAttributes();
            this._gripImageAttributes.ClearColorKey();
            switch (type)
            {
                case ScrollBarThumbDefaults.Normal:
                    this._color = SystemColors.ScrollBar;
                    this._gripColor = SystemColors.ControlText;
                    break;

                case ScrollBarThumbDefaults.Highlight:
                    this._color = SystemColors.ControlText;
                    this._gripColor = SystemColors.HighlightText;
                    break;
            }
            this._borderStyle = ScrollBarBorderStyle.Solid;
            this._borderColor = SystemColors.ControlText;
            this._gradientColor = new Resco.Controls.ScrollBar.GradientColor(FillDirection.Horizontal);
            this._gradientColor.PropertyChanged += new EventHandler(this.GradientColor_PropertyChanged);
            this._image = null;
            this._imageLayout = ScrollBarThumbImageLayout.Stretch;
            this._imageTransparentColor = System.Drawing.Color.Transparent;
            this._gripStyle = ScrollBarThumbGripStyle.Lines;
            this._gripImage = null;
            this._gripImageTransparentColor = System.Drawing.Color.Transparent;
            this._gripLines = 3;
        }
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            org = System.Drawing.Image.FromStream(fileUpload_Steg.PostedFile.InputStream);
            OriginalImage = (Bitmap)org;

            // Copy the original message.
            EncodedImage = (Bitmap)OriginalImage.Clone();
            MarkedImage = (Bitmap)OriginalImage.Clone();

            // Encode.
            try
            {
                string fileName = fileUpload_Steg.PostedFile.FileName;
                EncodeMessageInImage(EncodedImage, MarkedImage,
                    tb_pw.Text, tb_textToHide.Text);

                afterEncode = (System.Drawing.Image)EncodedImage;
                afterEncode.Save(Path.Combine(Server.MapPath(null), fileName));

                fileName = Path.Combine(Server.MapPath(null), fileName);
                //string fileName = img_userImage.ImageUrl;

                Response.ContentType = "image/JPEG";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + "watermarked_" + fileName.Remove(0, 15));

                Response.TransmitFile(fileName);
                Response.End();

            }
            catch (Exception ex)
            {

            }
        }
Example #9
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ColorMatrixManager.Grayscale(Value).Apply(img);
     }
 }
Example #10
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ConvolutionMatrixManager.GaussianBlur().Apply(img);
     }
 }
Example #11
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ColorMatrixManager.ChangeGamma(img, Value);
     }
 }
Example #12
0
 public bool Alert(Form Owner, string Message, Image Image = null)
 {
     action.Caption = "សំគាល់";
     action.Description = Message;
     action.Image = Image;
     return Show(Owner, action, properties, canCloseFunc) == DialogResult.Yes;
 }
Example #13
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ColorMatrixManager.Polaroid().Apply(img);
     }
 }
 private void CompareAndSave(string filename, Image testImage, ICommandAdapter adapter) {
     var threshold = this.ParameterValue<byte>("ImageDiffThreshold", 3);
     var localImage = Image.FromFile(filename);
     var masks = GetMasks(adapter).ToArray();
     var validDiffPercentace = this.ParameterValue("ValidDiffPercentage", 10);
     if (!masks.Any()) {
         var maskRectangle = GetMaskRectangle(adapter);
         if (maskRectangle != Rectangle.Empty) {
             CreateMask(filename, testImage, maskRectangle);                    
         } else {
             maskRectangle=new Rectangle(0,0,testImage.Width-1,testImage.Height-1);
         }
         var isValidPercentage = IsValidPercentage(testImage, maskRectangle, threshold, validDiffPercentace, localImage);
         if (!isValidPercentage)
             SaveImages(filename, testImage, threshold, localImage, maskRectangle);
     }
     var height = this.ParameterValue("MaskHeight", 0);
     var width = this.ParameterValue("MaskWidth", 0);
     foreach (var mask in masks) {
         var maskImage = mask;
         if (width > 0 && height > 0) {
             maskImage = (Bitmap)maskImage.ResizeRectangle(width, height);
         }
         var isValidPercentage = IsValidPercentage(testImage, maskImage, threshold, validDiffPercentace, localImage);
         if (!isValidPercentage)
             SaveImages(filename, testImage, threshold, localImage, maskImage);
     }
 }
 public DStarLiteForm()
 {
     InitializeComponent();
     My_D_Star_Lite = new D_Star_Lite();
     My_D_Star_Lite.Initial(Map_column, Map_row);
     New_Obstacle_List = new ArrayList();
     Team_List = new ArrayList();
     Alliance_List = new ArrayList();
     Enemy_list = new ArrayList();
     Get_Path = new ArrayList();
     Obstacle_List = new ArrayList();
     Updated_Nodes = new ArrayList();
     Path = new ArrayList();
     Map_Graphic = this.CreateGraphics();
     Re_Open_Nodes = Properties.Resources.Circle;
     Closed_Nodes = Properties.Resources.Circle_Cross;
     Robot = Properties.Resources.Robot1;
     New_Obs = Properties.Resources.RectangleWithCross;
     Path_Node = Properties.Resources.Empty_Rec;
     Round_Obstacle = Properties.Resources.Round;
     Triangle_Obstacle = Properties.Resources.Triangle;
     Target = Properties.Resources._5edge_Star;
     Rect_Obstacle = Properties.Resources.Rec_Obs;
     //mymap = new Grid_Map(Map_column, Map_row, 0, 0, Map_Graphic);
     Map_Background = Properties.Resources.Background;
     Map_Graphic.DrawImage(Map_Background, new Point(0, 0));
     Move_Button.Enabled = false;
 }
Example #16
0
        public static ImageData PrepareImage(Image img, TaskSettings taskSettings)
        {
            ImageData imageData = new ImageData();
            imageData.ImageFormat = taskSettings.ImageSettings.ImageFormat;

            if (taskSettings.ImageSettings.ImageFormat == EImageFormat.JPEG)
            {
                img = ImageHelpers.FillBackground(img, Color.White);
            }

            imageData.ImageStream = SaveImage(img, taskSettings.ImageSettings.ImageFormat, taskSettings);

            int sizeLimit = taskSettings.ImageSettings.ImageSizeLimit * 1000;

            if (taskSettings.ImageSettings.ImageFormat != taskSettings.ImageSettings.ImageFormat2 && sizeLimit > 0 && imageData.ImageStream.Length > sizeLimit)
            {
                if (taskSettings.ImageSettings.ImageFormat2 == EImageFormat.JPEG)
                {
                    img = ImageHelpers.FillBackground(img, Color.White);
                }

                imageData.ImageStream = SaveImage(img, taskSettings.ImageSettings.ImageFormat2, taskSettings);
                imageData.ImageFormat = taskSettings.ImageSettings.ImageFormat2;
            }

            return imageData;
        }
Example #17
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ConvolutionMatrixManager.EdgeDetect().Apply(img);
     }
 }
Example #18
0
        public PolygonRegion(Image backgroundImage = null)
            : base(backgroundImage)
        {
            nodes = new List<NodeObject>();

            MouseDown += PolygonRegionSurface_MouseDown;
        }
Example #19
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ConvolutionMatrixManager.MeanRemoval().Apply(img);
     }
 }
Example #20
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ColorMatrixManager.Saturation(Value).Apply(img);
     }
 }
Example #21
0
        public static Image SetImageOpacity(Image image, float opacity)
        {
            try
            {
                //create a Bitmap the size of the image provided
                var bmp = new Bitmap(image.Width, image.Height);

                //create a graphics object from the image
                using (var gfx = Graphics.FromImage(bmp))
                {
                    //create a color matrix object
                    var matrix = new ColorMatrix();

                    //set the opacity
                    matrix.Matrix33 = opacity;

                    //create image attributes
                    var attributes = new ImageAttributes();

                    //set the color(opacity) of the image
                    attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                    //now draw the image
                    gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height,
                        GraphicsUnit.Pixel, attributes);
                }
                return bmp;
            }
            catch
            {
                return null;
            }
        }
Example #22
0
 public static Image GetReducedImage(Image image, int extremeWidth, int extremeHeight) {
     double ratio = (double)image.Width / (double)image.Height;
     Size size = new Size(extremeWidth, (int)(extremeWidth / ratio));
     if(size.Height > extremeHeight)
         size = new Size((int)(extremeHeight * ratio), extremeHeight);
     return new Bitmap(image, size);
 }
 public byte[] ImageToByteArray(Image imageIn, string imageFormatString)
 {
     var ms = new MemoryStream();
     var imageFormat = getImageFormat(imageFormatString);
     imageIn.Save(ms, imageFormat);
     return ms.ToArray();
 }
Example #24
0
 public override Image Apply(Image img)
 {
     using (img)
     {
         return ColorMatrixManager.BlackWhite().Apply(img);
     }
 }
Example #25
0
        public TriangleRegion(Image backgroundImage = null)
            : base(backgroundImage)
        {
            Angle = TriangleAngle.Top;

            KeyDown += TriangleRegion_KeyDown;
        }
 public ElementImageComparer(IPurpleElement element)
 {
     this.element = element;
     CreateDirectory();
     liveImage = GetLiveImage();
     storedImage = GetStoredImage();
 }
Example #27
0
        /// <summary>
        /// resmi yeniden boyutlandır.
        /// </summary>
        /// <param name="imgToResize">boyutlandırılacak resim</param>
        /// <param name="size">boyutlar</param>
        /// <returns>Image titipnde bir resim</returns>
        public static Image ResizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            imgToResize.Dispose();

            return (Image)b;
        }
Example #28
0
        public static Image Resize(Image source, Size size)
        {
            int width = source.Width;
            int height = source.Height;

            float num3 = 0f;
            float num4 = 0f;
            float num5 = 0f;

            num4 = ((float)size.Width) / ((float)width);
            num5 = ((float)size.Height) / ((float)height);

            if (num5 < num4)
            {
                num3 = num5;
            }
            else
            {
                num3 = num4;
            }

            int num6 = (int)(width * num3);
            int num7 = (int)(height * num3);

            Bitmap image = new Bitmap(num6, num7);

            using (Graphics graphics = Graphics.FromImage(image))
            {
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.DrawImage(source, 0, 0, num6, num7);
            }

            return image;
        }
Example #29
0
 public static Image ResizeImage(Image image, Size size, bool preserveAspectRatio = true)
 {
     int newWidth;
     int newHeight;
     if (preserveAspectRatio)
     {
         int originalWidth = image.Width;
         int originalHeight = image.Height;
         float percentWidth = size.Width / (float)originalWidth;
         float percentHeight = size.Height / (float)originalHeight;
         float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
         newWidth = (int)(originalWidth * percent);
         newHeight = (int)(originalHeight * percent);
     }
     else
     {
         newWidth = size.Width;
         newHeight = size.Height;
     }
     Image newImage = new Bitmap(newWidth, newHeight);
     using (Graphics graphicsHandle = Graphics.FromImage(newImage))
     {
         graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
         graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
     }
     return newImage;
 }
        public void ProcessImage()
        {
            if (_isFirst)
            {
                _nextImage = _prevImage = _image.Convert<Gray, byte>();
                _isFirst = !_isFirst;
            }
            else
            {
                _prevImage = _nextImage;
                _nextImage = _image.Convert<Gray, byte>();
                var imageResult = TinhSuChenhLech();
                _lstRectangles = _videoUlity.DetectBlock(imageResult, imageResult.Width, imageResult.Height);

                //draw rectangle
                foreach (var rectangle in _lstRectangles)
                {
                    var drawRec = new Rectangle(
                    rectangle.X,
                    rectangle.Y,
                    rectangle.Size.Width,
                    rectangle.Size.Height
                    );
                    _image.Draw(drawRec, new Bgr(Color.Yellow), 2);
                }
                _picScreen.Image = _image.Clone().ToBitmap();
            }
        }
Example #31
0
        public static byte[] ToByteArray(this Drawing.Image image, Drawing.Imaging.ImageFormat format)
        {
            using (var stream = new MemoryStream())
            {
                image.Save(stream, format);

                stream.Position = 0;

                return(stream.ToArray());
            }
        }
Example #32
0
 public static int alturaImg(string diretorioImg)
 {
     System.Drawing.Image img = System.Drawing.Image.FromFile(diretorioImg);
     return(img.Height);
 }
Example #33
0
 public static byte[] ToByteArray(this Drawing.Image image) => image.ToByteArray(Drawing.Imaging.ImageFormat.Bmp);
Example #34
0
 public void onClickImage()
 {
 System.Drawing.Image img = System.Drawing.Image.FromFile(face3);

 ProcessImage(img);
 }
Example #35
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["up"] != null)
        {
            HttpFileCollection files = Request.Files;
            if (files.Count == 0)
            {
                Response.Write("请选择要上传的文件");
            }
            else if (Request["kind"] == "img")
            {
                string dir   = Settings.BasePath + "upload\\images\\" + DateTime.Now.ToString("yyyyMM");
                string fname = dir + "\\" + DateTime.Now.ToString("ddhhmmss") + DateTime.Now.Millisecond.ToString();
                string fn    = files[0].FileName;
                fname += fn.Substring(fn.LastIndexOf("."));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                files[0].SaveAs(fname);

                script = "top.loat('" + fname.Replace(Settings.BasePath, Settings.BaseURL).Replace("\\", "/") + "');";
            }
            else if (Request["kind"] == "group")
            {
                string gid = Request["data"];

                string newpath = Server.MapPath("/upload/group/" + gid + ".jpg");
                string s       = newpath.Replace(".jpg", "-s.jpg");

                Tools.MakeThumbnail("", files[0].InputStream, newpath, bigWidth);
                Tools.MakeThumbnail("", files[0].InputStream, s, smallWidth);

                script = "top.loat();";
            }
            else
            {
                string newpath = Server.MapPath("/upload/photo/" + CKUser.Username + ".jpg");
                string b       = newpath.Replace(".jpg", "-b.jpg");
                string s       = newpath.Replace(".jpg", "-s.jpg");

                files[0].SaveAs(b);

                Stream imgStream = files[0].InputStream;

                Tools.MakeThumbnail("", imgStream, newpath, bigWidth);
                Tools.MakeThumbnail("", imgStream, s, smallWidth);

                System.Drawing.Image img = System.Drawing.Image.FromStream(imgStream);
                if (img.Width < bigWidth + 30)
                {
                    script = "top.loat(false);";
                }
                else
                {
                    script = "top.loat(true);";
                }
            }
        }
        if (Request["cutimg"] != null)
        {
            int    x      = int.Parse(Request["x1"]);
            int    y      = int.Parse(Request["y1"]);
            int    width  = int.Parse(Request["x2"]) - x;
            int    height = int.Parse(Request["y2"]) - y;
            string b      = Server.MapPath("/upload/photo/" + CKUser.Username + "-b.jpg");
            string p      = b.Replace("-b.jpg", ".jpg");
            Tools.MakeThumbnail(b, p, x, y, width, height);
            IO.DeleteFile(b);
            Tools.MakeThumbnail(p, null, b.Replace("-b.jpg", "-s.jpg"), smallWidth);

            Response.Write("<img src='/upload/photo/" + CKUser.Username + ".jpg' />");
            Response.End();
        }
    }
Example #36
0
    protected bool Validate()
    {
        bool blnReturn = false;

        divError.Visible = false;
        string strErrorMessage = "";

        if (hndGroupUpdateCode.Value == string.Empty && hndIsPreview.Value == string.Empty)
        {
            if (hdnGroupHead.Value.Length == 0)
            {
                strErrorMessage += "No group head has been assigned to your department, please contact your system administrator.<br/>";
            }

            if (!fuAttachment.HasFile)
            {
                strErrorMessage += "Image attachement is required.<br/>";
            }

            if (fuAttachment.FileName.Contains(".jpg") || fuAttachment.FileName.Contains(".jpeg") || fuAttachment.FileName.Contains(".png") || fuAttachment.FileName.Contains(".JPG") || fuAttachment.FileName.Contains(".JPEG") || fuAttachment.FileName.Contains(".PNG") || fuAttachment.FileName.Contains(".GIF") || fuAttachment.FileName.Contains(".gif"))
            {
                System.Drawing.Image uploadedImage = System.Drawing.Image.FromStream(fuAttachment.PostedFile.InputStream);
                Single height = uploadedImage.PhysicalDimension.Height;
                Single width  = uploadedImage.PhysicalDimension.Width;

                if (height != 250 || width != 420)
                {
                    strErrorMessage += " Image dimension must be exactly 420 pixels for width and 250 pixels for height.<br>";
                }
            }
            else
            {
                strErrorMessage += "Only the following format will be accepted <b>.JPG, .JPEG and .PNG</b>.<br/>";
            }
        }
        else
        {
            if (fuAttachment.HasFile)
            {
                if (fuAttachment.FileName.Contains(".jpg") || fuAttachment.FileName.Contains(".jpeg") || fuAttachment.FileName.Contains(".png") || fuAttachment.FileName.Contains(".JPG") || fuAttachment.FileName.Contains(".JPEG") || fuAttachment.FileName.Contains(".PNG") || fuAttachment.FileName.Contains(".GIF") || fuAttachment.FileName.Contains(".gif"))
                {
                    System.Drawing.Image uploadedImage = System.Drawing.Image.FromStream(fuAttachment.PostedFile.InputStream);
                    Single height = uploadedImage.PhysicalDimension.Height;
                    Single width  = uploadedImage.PhysicalDimension.Width;

                    if (height != 250 || width != 420)
                    {
                        strErrorMessage += " Image dimension must be exactly 420 pixels for width and 250 pixels for height.<br>";
                    }
                }
                else
                {
                    strErrorMessage += "Only the following format will be accepted <b>.JPG, .JPEG and .PNG</b>.<br/>";
                }
            }
        }


        if (strErrorMessage.Length > 0)
        {
            divError.Visible = true;
            lblErrMsg.Text   = strErrorMessage;
            blnReturn        = false;
        }
        else
        {
            blnReturn = true;
        }


        return(blnReturn);
    }
Example #37
0
    protected void btnSave_Emp_Click1(object sender, EventArgs e)
    {
        if (termscond.Checked == true)
        {
            if (IsValid)
            {
                string exyr   = "";
                string exmn   = "";
                string fnar   = "";
                string cind   = "";
                string exyr1  = "";
                string exmn1  = "";
                string fnar1  = "";
                string cind1  = "";
                string exyr2  = "";
                string exmn2  = "";
                string fnar2  = "";
                string cind2  = "";
                string sk1    = "";
                string sk1yr  = "";
                string sk1mnt = "";
                string sk1ex  = "";
                string sk2    = "";
                string sk2yr  = "";
                string sk2mnt = "";
                string sk2ex  = "";
                string sk3    = "";
                string sk3yr  = "";
                string sk3mnt = "";
                string sk3ex  = "";
                string sk4    = "";
                string sk4yr  = "";
                string sk4mnt = "";
                string sk4ex  = "";
                string sk5    = "";
                string sk5yr  = "";
                string sk5mnt = "";
                string sk5ex  = "";
                string sk6    = "";
                string sk6yr  = "";
                string sk6mnt = "";
                string sk6ex  = "";

                string ed1   = "";
                string ed1bd = "";
                string ed1sb = "";
                string ed1y  = "";
                string ed1pe = "";
                string ed2   = "";
                string ed2bd = "";
                string ed2sb = "";
                string ed2y  = "";
                string ed2pe = "";
                string ed3   = "";
                string ed3bd = "";
                string ed3sb = "";
                string ed3y  = "";
                string ed3pe = "";

                string ed4   = "";
                string ed4bd = "";
                string ed4sb = "";
                string ed4y  = "";
                string ed4pe = "";

                string ed5   = "";
                string ed5bd = "";
                string ed5sb = "";
                string ed5y  = "";
                string ed5pe = "";

                string rtit       = "";
                string rfil       = "";
                string stras      = "";
                string rpath      = "";
                string rtxt       = "";
                string pdt        = "";
                int    status     = 0;
                string Mar_status = "";
                string prco       = "";
                string prsta      = "";
                string prcity     = "";
                string praddress  = "";
                string przp       = "";
                string prwp       = "";
                string prhp       = "";
                string rphoto     = "";
                string photopath  = "";

                exyr   = Convert.ToString(expyrs.Text);
                exyr1  = Convert.ToString(expyrs1.Text);
                exyr2  = Convert.ToString(expyrs2.Text);
                exmn   = Convert.ToString(expmon.Text);
                exmn1  = Convert.ToString(expmon1.Text);
                exmn2  = Convert.ToString(expmon2.Text);
                fnar   = Convert.ToString(fnarea.Text);
                fnar1  = Convert.ToString(fnarea1.Text);
                fnar2  = Convert.ToString(fnarea2.Text);
                cind   = Convert.ToString(currind.Text);
                cind1  = Convert.ToString(currind1.Text);
                cind2  = Convert.ToString(currind2.Text);
                sk1    = Convert.ToString(skills1.Text);
                sk1yr  = Convert.ToString(sk1yrs.Text);
                sk1mnt = Convert.ToString(sk1mnts.Text);
                sk1ex  = Convert.ToString(sk1exp.SelectedItem.Text);
                sk2    = Convert.ToString(skills2.Text);
                sk2yr  = Convert.ToString(sk2yrs.Text);
                sk2mnt = Convert.ToString(sk2mnts.Text);
                sk2ex  = Convert.ToString(sk2exp.SelectedItem.Text);
                sk3    = Convert.ToString(skills3.Text);
                sk3yr  = Convert.ToString(sk3yrs.Text);
                sk3mnt = Convert.ToString(sk3mnts.Text);
                sk3ex  = Convert.ToString(sk3exp.SelectedItem.Text);
                sk4    = Convert.ToString(skills4.Text);
                sk4yr  = Convert.ToString(sk4yrs.Text);
                sk4mnt = Convert.ToString(sk4mnts.Text);
                sk4ex  = Convert.ToString(sk4exp.SelectedItem.Text);
                sk5    = Convert.ToString(skills5.Text);
                sk5yr  = Convert.ToString(sk5yrs.Text);
                sk5mnt = Convert.ToString(sk5mnts.Text);
                sk5ex  = Convert.ToString(sk5exp.SelectedItem.Text);
                sk6    = Convert.ToString(skills6.Text);
                sk6yr  = Convert.ToString(sk6yrs.Text);
                sk6mnt = Convert.ToString(sk6mnts.Text);
                sk6ex  = Convert.ToString(sk6exp.SelectedItem.Text);

                ed1   = Convert.ToString(edu1.Text);
                ed1bd = Convert.ToString(ed1brd.Text);
                ed1sb = Convert.ToString(ed1sub.Text);
                ed1y  = Convert.ToString(ed1yr.Text);
                ed1pe = Convert.ToString(ed1per.Text);

                ed2   = Convert.ToString(edu2.Text);
                ed2bd = Convert.ToString(ed2brd.Text);
                ed2sb = Convert.ToString(ed2sub.Text);
                ed2y  = Convert.ToString(ed2yr.Text);
                ed2pe = Convert.ToString(ed2per.Text);

                ed3   = Convert.ToString(edu3.Text);
                ed3bd = Convert.ToString(ed3brd.Text);
                ed3sb = Convert.ToString(ed3sub.Text);
                ed3y  = Convert.ToString(ed3yr.Text);
                ed3pe = Convert.ToString(ed3per.Text);

                ed4   = Convert.ToString(edu4.Text);
                ed4bd = Convert.ToString(ed4brd.Text);
                ed4sb = Convert.ToString(ed4sub.Text);
                ed4y  = Convert.ToString(ed4yr.Text);
                ed4pe = Convert.ToString(ed4per.Text);

                ed5   = Convert.ToString(edu5.Text);
                ed5bd = Convert.ToString(ed5brd.Text);
                ed5sb = Convert.ToString(ed5sub.Text);
                ed5y  = Convert.ToString(ed5yr.Text);
                ed5pe = Convert.ToString(ed5per.Text);

                rtit = Convert.ToString(restitle.Text);
                //rfil = Convert.ToString(System.IO.Path.GetFileName(rfile.PostedFile.FileName));
                string Base_dir = System.AppDomain.CurrentDomain.BaseDirectory;
                if (rfile.HasFile)
                {
                    rfil  = Path.GetFileName(rfile.PostedFile.FileName);
                    stras = rfil;
                    rpath = "Resume/" + stras.ToString();
                    string rpath1 = "admin/Resumes/" + stras.ToString();
                    rfile.SaveAs(Base_dir + rpath);
                    rfile.SaveAs(Base_dir + rpath1);
                }
                else
                {
                    rpath = "";
                }
                if (Fileupphoto.HasFile)
                {
                    rphoto = Fileupphoto.FileName.ToString();
                    //string st_img = System.IO.Path.GetFullPath(Fileupphoto.PostedFile.FileName);
                    //string st = System.IO.Directory.GetCurrentDirectory();\
                    using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(Fileupphoto.PostedFile.InputStream))
                    {
                        if (myImage.Height == 135 && myImage.Width == 135)
                        {
                            photopath = Base_dir + "Emp_photos/" + rphoto;
                            string photopath1 = Base_dir + "admin/Emp_photos/" + rphoto;
                            Fileupphoto.SaveAs(photopath);
                            Fileupphoto.SaveAs(photopath1);
                        }
                        else
                        {
                            strScript = "alert('Image size is Too Large')";
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", strScript, true);
                        }
                    }
                }
                else
                {
                    photopath = "";
                }
                rtxt = Convert.ToString(txtres.Text);
                //pplc = Convert.ToString(pplace.Text);
                pdt    = (System.DateTime.Today.Date).ToString();
                status = 0;
                Random rs        = new Random();
                string Active_Id = Convert.ToString(rs.Next(10000));
                try
                {
                    connection.Open();
                    string strQry = "update employeereg1 set totexptrs=@exyr, totexpmonths=@exmn, rhead=@rtit, functionalarea=@fnar," +
                                    " currentindustrytype=@cind, skills1=@sk1, sk1years=@sk1yr,sk1months=@sk1mnt, sk1exp=@sk1ex, skills2=@sk2, " +
                                    "sk2years=@sk2yr,sk2months=@sk2mnt, sk2exp=@sk2ex, skills3=@sk3, sk3years=@sk3yr,sk3months=@sk3mnt, sk3exp=@sk3ex," +
                                    "skills4=@sk4, sk4years=@sk4yr,sk4months=@sk4mnt, sk4exp=@sk4ex,skills5=@sk5, sk5years=@sk5yr,sk5months=@sk5mnt," +
                                    " sk5exp=@sk5ex,skills6=@sk6, sk6years=@sk6yr,sk6months=@sk6mnt, sk6exp=@sk6ex, edu1=@ed1, ed1brd=@ed1bd, ed1sub=@ed1sb," +
                                    " ed1year=@ed1y, ed1per=@ed1pe, edu2=@ed2, ed2brd=@ed2bd, ed2sub=@ed2sb, ed2year=@ed2y, ed2per=@ed2pe, edu3=@ed3, " +
                                    "ed3brd=@ed3bd, ed3sub=@ed3sb, ed3year=@ed3y, ed3per=@ed3pe, edu4=@ed4, ed4brd=@ed4bd, ed4sub=@ed4sb, ed4year=@ed4y," +
                                    " ed4per=@ed4pe, edu5=@ed5, ed5brd=@ed5bd, ed5sub=@ed5sb, ed5year=@ed5y, ed5per=@ed5pe, filename1=@rfil, resumetxt=@rtxt," +
                                    " pdate=@pdate, status=@status,totexptrs1=@exyr1,totexptrs2=@exyr2,totexpmonths1=@exmn1,totexpmonths2=@exmn2," +
                                    "functionalarea1=@fnar1,functionalarea2=@fnar2,previousindustrytype1=@cind1,previousindustrytype2=@cind2,rpath=@rpath," +
                                    "Activeid=@Active_Id,photo=@pic,photopath=@picpath where userid= " + val;

                    SqlCommand cmd = new SqlCommand(strQry, connection);

                    cmd.Parameters.Add(new SqlParameter("@exyr", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@exmn", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@rtit", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@fnar", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@cind", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@sk1", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk1yr", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk1mnt", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk1ex", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@sk2", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk2yr", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk2mnt", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk2ex", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@sk3", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk3yr", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk3mnt", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk3ex", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@sk4", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk4yr", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk4mnt", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk4ex", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@sk5", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk5yr", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk5mnt", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk5ex", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@sk6", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk6yr", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk6mnt", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@sk6ex", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@ed1", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed1bd", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed1sb", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed1y", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed1pe", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@ed2", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed2bd", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed2sb", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed2y", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed2pe", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@ed3", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed3bd", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed3sb", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed3y", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed3pe", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@ed4", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed4bd", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed4sb", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed4y", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed4pe", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@ed5", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed5bd", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed5sb", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed5y", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@ed5pe", SqlDbType.NVarChar, 50));

                    cmd.Parameters.Add(new SqlParameter("@rfil", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@rtxt", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@pdate", SqlDbType.DateTime, 20));
                    cmd.Parameters.Add(new SqlParameter("@status", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@exyr1", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@exyr2", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@exmn1", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@exmn2", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@fnar1", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@fnar2", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@cind1", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@cind2", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@rpath", SqlDbType.NVarChar, 10000));
                    //cmd.Parameters.Add(new SqlParameter("@pplc", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@Active_Id", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@pic", SqlDbType.NVarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@picpath", SqlDbType.NVarChar, 10000));

                    if (exyr != "")
                    {
                        cmd.Parameters["@exyr"].Value = Convert.ToInt32(exyr);
                    }
                    else
                    {
                        cmd.Parameters["@exyr"].Value = 0;
                    }

                    if (exmn != "")
                    {
                        cmd.Parameters["@exmn"].Value = Convert.ToInt32(exmn);
                    }
                    else
                    {
                        cmd.Parameters["@exmn"].Value = 0;
                    }

                    if (exyr1 != "")
                    {
                        cmd.Parameters["@exyr1"].Value = Convert.ToInt32(exyr1);
                    }
                    else
                    {
                        cmd.Parameters["@exyr1"].Value = 0;
                    }

                    if (exmn1 != "")
                    {
                        cmd.Parameters["@exmn1"].Value = Convert.ToInt32(exmn1);
                    }
                    else
                    {
                        cmd.Parameters["@exmn1"].Value = 0;
                    }

                    if (exyr2 != "")
                    {
                        cmd.Parameters["@exyr2"].Value = Convert.ToInt32(exyr2);
                    }
                    else
                    {
                        cmd.Parameters["@exyr2"].Value = 0;
                    }

                    if (exmn2 != "")
                    {
                        cmd.Parameters["@exmn2"].Value = Convert.ToInt32(exmn2);
                    }
                    else
                    {
                        cmd.Parameters["@exmn2"].Value = 0;
                    }

                    cmd.Parameters["@rtit"].Value = rtit;
                    cmd.Parameters["@fnar"].Value = fnar;
                    cmd.Parameters["@cind"].Value = cind;

                    cmd.Parameters["@fnar1"].Value = fnar1;
                    cmd.Parameters["@cind1"].Value = cind1;
                    cmd.Parameters["@fnar2"].Value = fnar2;
                    cmd.Parameters["@cind2"].Value = cind2;

                    cmd.Parameters["@sk1"].Value    = sk1;
                    cmd.Parameters["@sk1yr"].Value  = sk1yr;
                    cmd.Parameters["@sk1mnt"].Value = sk1mnt;
                    cmd.Parameters["@sk1ex"].Value  = sk1ex;

                    cmd.Parameters["@sk2"].Value    = sk2;
                    cmd.Parameters["@sk2yr"].Value  = sk2yr;
                    cmd.Parameters["@sk2mnt"].Value = sk2mnt;
                    cmd.Parameters["@sk2ex"].Value  = sk2ex;

                    cmd.Parameters["@sk3"].Value    = sk3;
                    cmd.Parameters["@sk3yr"].Value  = sk3yr;
                    cmd.Parameters["@sk3mnt"].Value = sk3mnt;
                    cmd.Parameters["@sk3ex"].Value  = sk3ex;

                    cmd.Parameters["@sk4"].Value    = sk4;
                    cmd.Parameters["@sk4yr"].Value  = sk4yr;
                    cmd.Parameters["@sk4mnt"].Value = sk4mnt;
                    cmd.Parameters["@sk4ex"].Value  = sk4ex;

                    cmd.Parameters["@sk5"].Value    = sk5;
                    cmd.Parameters["@sk5yr"].Value  = sk5yr;
                    cmd.Parameters["@sk5mnt"].Value = sk5mnt;
                    cmd.Parameters["@sk5ex"].Value  = sk5ex;

                    cmd.Parameters["@sk6"].Value    = sk6;
                    cmd.Parameters["@sk6yr"].Value  = sk6yr;
                    cmd.Parameters["@sk6mnt"].Value = sk6mnt;
                    cmd.Parameters["@sk6ex"].Value  = sk6ex;

                    cmd.Parameters["@ed1"].Value   = ed1;
                    cmd.Parameters["@ed1bd"].Value = ed1bd;
                    cmd.Parameters["@ed1sb"].Value = ed1sb;
                    cmd.Parameters["@ed1y"].Value  = ed1y;
                    cmd.Parameters["@ed1pe"].Value = ed1pe;
                    cmd.Parameters["@ed2"].Value   = ed2;
                    cmd.Parameters["@ed2bd"].Value = ed2bd;
                    cmd.Parameters["@ed2sb"].Value = ed2sb;
                    cmd.Parameters["@ed2y"].Value  = ed2y;
                    cmd.Parameters["@ed2pe"].Value = ed2pe;
                    cmd.Parameters["@ed3"].Value   = ed3;
                    cmd.Parameters["@ed3bd"].Value = ed3bd;
                    cmd.Parameters["@ed3sb"].Value = ed3sb;
                    cmd.Parameters["@ed3y"].Value  = ed3y;
                    cmd.Parameters["@ed3pe"].Value = ed3pe;

                    cmd.Parameters["@ed4"].Value   = ed4;
                    cmd.Parameters["@ed4bd"].Value = ed4bd;
                    cmd.Parameters["@ed4sb"].Value = ed4sb;
                    cmd.Parameters["@ed4y"].Value  = ed4y;
                    cmd.Parameters["@ed4pe"].Value = ed4pe;

                    cmd.Parameters["@ed5"].Value   = ed5;
                    cmd.Parameters["@ed5bd"].Value = ed5bd;
                    cmd.Parameters["@ed5sb"].Value = ed5sb;
                    cmd.Parameters["@ed5y"].Value  = ed5y;
                    cmd.Parameters["@ed5pe"].Value = ed5pe;

                    cmd.Parameters["@rtxt"].Value    = rtxt;
                    cmd.Parameters["@rfil"].Value    = rfil;
                    cmd.Parameters["@rpath"].Value   = rpath;
                    cmd.Parameters["@pdate"].Value   = pdt;
                    cmd.Parameters["@status"].Value  = status;
                    cmd.Parameters["@pic"].Value     = rphoto;
                    cmd.Parameters["@picpath"].Value = photopath;

                    if (Active_Id != "")
                    {
                        cmd.Parameters["@Active_Id"].Value = Active_Id;
                    }
                    else
                    {
                        cmd.Parameters["@Active_Id"].Value = "NotGenerated";
                    }
                    int up = cmd.ExecuteNonQuery();
                    connection.Close();
                    if (up == 1)
                    {
                        //SendMailMessage(usid, fn, ln, pw);
                        strScript = "alert('All Details Registered successfully');location.replace('Default.aspx')";
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alertBox", strScript, true);
                        //SendMail(usid, fn, ln);
                    }
                }
                catch (Exception ex)
                {
                    //to catch exception handled
                    lblmail.Text = ex.Message;
                }
            }
        }
        else
        {
            strScript = "alert('Agree the Terms and Conditions.');";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alertBox", strScript, true);
        }
    }
Example #38
0
    protected void btnCadastrar_Click(object sender, EventArgs e)
    {
        hdf.Value = Session["value"].ToString();
        tra_transporte tra = new tra_transporte();
        string         arq;
        string         placa;
        string         dir = Request.PhysicalApplicationPath + "pg\\uploads\\";

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }

        foreach (HttpPostedFile flp in fup.PostedFiles)
        {
            double mp = 2000;

            if (fup.HasFile)
            {
                arq = Path.GetFileName(flp.FileName);
                string ext = Path.GetExtension(flp.FileName);
                ext = ext.ToLower();
                double ta = flp.ContentLength / 1024;

                if (ext == ".jpg" || ext == ".png" || ext == ".gif")
                {
                    if (ta <= mp)
                    {
                        arq = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ext;
                        if (!File.Exists(dir + arq))
                        {
                            flp.SaveAs(dir + arq);

                            System.Drawing.Image imgOriginal = System.Drawing.Image.FromFile(Server.MapPath("~/pg/uploads/" + arq), true);

                            System.Drawing.Image.GetThumbnailImageAbort miniatura = new System.Drawing.Image.GetThumbnailImageAbort(erro);

                            System.Drawing.Image imgRedimensionada;

                            int width, height;

                            if (imgOriginal.Width > 200)
                            {
                                width = 200; height = (int)(width * imgOriginal.Height) / imgOriginal.Width;
                            }
                            else
                            {
                                width = imgOriginal.Width; height = imgOriginal.Height;
                            }

                            imgRedimensionada = imgOriginal.GetThumbnailImage(width, height, miniatura, IntPtr.Zero);


                            imgRedimensionada.Dispose();

                            imgOriginal.Dispose();


                            tve_tipoveiculo tve = new tve_tipoveiculo();
                            tve.Tve_id = Convert.ToInt32(ddlVeiculo.SelectedValue);


                            tra.Tra_lugares = Convert.ToInt32(txtLugar.Text);
                            tra.Tra_modelo  = txtModelo.Text;
                            tra.Tra_ano     = Convert.ToInt32(txtAno.Text);
                            tra.Tra_placa   = txtPlaca.Text;
                            tra.Tve_id      = tve;
                            placa           = txtPlaca.Text;
                            tra_transporteDB.Insert(tra);

                            DataSet codigo = new DataSet();
                            codigo     = tra_transporteDB.SelectLugar(placa);
                            tra.Tra_id = Convert.ToInt32(codigo.Tables[0].Rows[0][0]);

                            img_imagemveiculo img = new img_imagemveiculo();
                            img.Img_foto = arq;
                            img.Tra_id   = tra;
                            img_imagemveiculoDB.Insert(img);



                            if (cb1.Checked)
                            {
                                rec_recursos rec = new rec_recursos();
                                rec.Rec_id = 1;

                                txr_transporte_recursos txr = new txr_transporte_recursos();
                                txr.Tra_id = tra;
                                txr.Rec_id = rec;

                                txr_transporte_recursosDB.Insert(txr);
                            }
                            if (cb2.Checked)
                            {
                                rec_recursos rec = new rec_recursos();
                                rec.Rec_id = 2;

                                txr_transporte_recursos txr = new txr_transporte_recursos();
                                txr.Tra_id = tra;
                                txr.Rec_id = rec;

                                txr_transporte_recursosDB.Insert(txr);
                            }
                            if (cb3.Checked)
                            {
                                rec_recursos rec = new rec_recursos();
                                rec.Rec_id = 3;

                                txr_transporte_recursos txr = new txr_transporte_recursos();
                                txr.Tra_id = tra;
                                txr.Rec_id = rec;

                                txr_transporte_recursosDB.Insert(txr);
                            }
                            if (cb4.Checked)
                            {
                                rec_recursos rec = new rec_recursos();
                                rec.Rec_id = 4;

                                txr_transporte_recursos txr = new txr_transporte_recursos();
                                txr.Tra_id = tra;
                                txr.Rec_id = rec;

                                txr_transporte_recursosDB.Insert(txr);
                            }
                            if (cb5.Checked)
                            {
                                rec_recursos rec = new rec_recursos();
                                rec.Rec_id = 5;

                                txr_transporte_recursos txr = new txr_transporte_recursos();
                                txr.Tra_id = tra;
                                txr.Rec_id = rec;

                                txr_transporte_recursosDB.Insert(txr);
                            }
                            if (cb6.Checked)
                            {
                                rec_recursos rec = new rec_recursos();
                                rec.Rec_id = 6;

                                txr_transporte_recursos txr = new txr_transporte_recursos();
                                txr.Tra_id = tra;
                                txr.Rec_id = rec;

                                txr_transporte_recursosDB.Insert(txr);
                            }

                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalS();", true);
                        }
                        else
                        {
                            //Response.Write("<script>alert('Arquivo ja existe');</script>");
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalF();", true);
                        }
                    }
                    else
                    {
                        //Response.Write("<script>alert('Tamanho maximo excedido - 500KB');</script>");
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalMS();", true);
                    }
                }
                else
                {
                    //Response.Write("<script>alert('Extensão invalida');</script>");
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalEI();", true);
                }
            }
            else
            {
                //Response.Write("<script>alert('Selecione um arquivo');</script>");
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalSl();", true);
            }
        }

        DataSet idMot = new DataSet();

        idMot = mot_motoristaDB.SelectID(Convert.ToInt32(hdf.Value));

        mot_motorista mot = new mot_motorista();

        mot.Mot_id = Convert.ToInt32(idMot.Tables[0].Rows[0][0]);

        txm_transporte_motorista txm = new txm_transporte_motorista();

        txm.Mot_id = mot;
        txm.Tra_id = tra;
        txm_transporte_motoristaDB.Insert(txm);
    }
    protected void UpdateButton_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            try
            {
                Employee employee = EB.GetEmployee(employeeId);
                if (EB.IsExist(txtEmail.Text.Trim()) && !employee.Employee_Email.Equals(txtEmail.Text.Trim()))
                {
                    pnlRed.Visible = true;
                    lblError.Text  = "This email have already used.";
                    return;
                }

                String data = "";
                if (fuAvatar.HasFile)
                {
                    System.Drawing.Image image = System.Drawing.Image.FromStream(fuAvatar.PostedFile.InputStream);
                    data = WebHelper.Instance.ImageToBase64(image, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    String gender = "";
                    if (employee.Employee_Gender)
                    {
                        gender = "Male";
                    }
                    else
                    {
                        gender = "Female";
                    }

                    if (!gender.Equals(radGender.Text.Trim()))
                    {
                        // Picture male default
                        String filePathMale         = WebHelper.Instance.GetWebsitePath() + "App_Themes/images/other/male.png";
                        System.Drawing.Image imageM = System.Drawing.Image.FromFile(filePathMale);
                        String dataMale             = WebHelper.Instance.ImageToBase64(imageM, System.Drawing.Imaging.ImageFormat.Png);

                        // Picture female default
                        String filePathFemale       = WebHelper.Instance.GetWebsitePath() + "App_Themes/images/other/female.png";
                        System.Drawing.Image imageF = System.Drawing.Image.FromFile(filePathFemale);
                        String dataFemale           = WebHelper.Instance.ImageToBase64(imageF, System.Drawing.Imaging.ImageFormat.Png);

                        if (employee.Employee_Avatar.Equals(dataMale))
                        {
                            data = dataFemale;
                        }
                        else if (employee.Employee_Avatar.Equals(dataFemale))
                        {
                            data = dataMale;
                        }
                        else
                        {
                            data = null;
                        }
                    }
                    else
                    {
                        data = null;
                    }
                }
                EB.UpdateEmployee(employee.Employee_Id, new Guid(ddlDepartment.SelectedValue), txtFName.Text.Trim(), txtLName.Text.Trim(), txtEmail.Text.Trim(), txtAddress.Text.Trim(), txtPhoneNumber.Text.Trim(), radGender.Text, txtDOB.Text.Trim(), data);
                if (Session["return"] == null)
                {
                    Session.Add("return", "Emodify");
                }
                else
                {
                    Session["return"] = "Emodify";
                }
                Response.Redirect(WebHelper.Instance.GetURL() + "ManageSystem/Employee/Manage/" + employee.Employee_Id.ToString());
            }
            catch (Exception ex)
            {
                pnlRed.Visible       = true;
                lblError.Text        = ex.Message;
                hplnkRed.Text        = "Please try again.";
                hplnkRed.NavigateUrl = "";
                Employee employee = EB.GetEmployee(employeeId);
                imgAvatar.ImageUrl = WebHelper.Instance.GetImageURL(employee.Employee_Avatar, 128, 128, false);
            }
        }
    }
Example #40
0
 public static int larguraImg(string diretorioImg)
 {
     System.Drawing.Image img = System.Drawing.Image.FromFile(diretorioImg);
     return(img.Width);
 }
    public void GetDetailProduct(DataTable table, DataTable add, DataTable promotion, DataTable viewpro, DataTable MultiImg)
    {
        try
        {
            if (table.Rows.Count > 0)
            {
                string strid   = table.Rows[0]["Id"].ToString();
                string strname = table.Rows[0]["Name"].ToString() + " " + table.Rows[0]["state"].ToString();
                string strurl  = table.Rows[0]["UrlImage"].ToString();
                if (strurl.Length > 0)
                {
                    strurl = "image/img_pro/" + strurl;
                }
                else
                {
                    strurl = "image/common/notimgpro.png";
                }
                float  rate   = (float)Application["ratepromain"];
                float  price1 = 1;
                string price2 = table.Rows[0]["SellingPrice"].ToString();
                price1 = float.Parse(table.Rows[0]["SellingPrice"].ToString());
                price1 = price1 * rate;
                string strprice    = price1.ToString("N").Split('.')[0];
                string strwarranty = table.Rows[0]["WarrantyMonth"].ToString();
                string strBrand    = table.Rows[0]["Brand"].ToString();
                string stridbrand  = table.Rows[0]["idbrand"].ToString();
                string strnote     = table.Rows[0]["Note"].ToString();
                string strdes      = table.Rows[0]["des"].ToString();
                string isspec      = table.Rows[0]["Isspec"].ToString();;
                tcurrentAccess += "<a href='default.aspx?menu=pro&brand=" + stridbrand + "' onmouseover='OnMOMenu(" + stridbrand + ",0,10,event);' onmouseout='TimeHidden();'>" + strBrand + "</a> &raquo; " + strname;
                //strpro = "<div id='divVideo' class='dvideo' style='display:none;'><object width='335' height='360'><param name='movie' value='http://www.cnet.com/av/video/flv/newPlayers/universal.swf' /><param name='wmode' value='transparent' /><param name='allowFullScreen' value='true' /><param name='FlashVars' value='playerType=embedded&value=29433' /><embed src='http://www.cnet.com/av/video/flv/newPlayers/universal.swf' type='application/x-shockwave-flash' wmode='transparent' width='335' height='360' allowFullScreen='true' FlashVars='playerType=embedded&value=29433' /></object>";
                //strpro += "<div style='width:100px' class='text_title' onclick='Openvideo(0);'><a href='#'>Đóng lại</a></div></div>";
                if (isspec.Equals("1"))
                {
                    strpro += "<table width='100%' cellpadding='0' cellspacing='0' border='0' class='cl1'>";
                }
                else
                {
                    strpro += "<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
                }
                string imgAd      = "";
                string seeMore    = "";
                string divseeMore = "";
                string listImg    = "";
                if (MultiImg.Rows.Count > 0)
                {
                    imgAd = MultiImg.Rows[0]["img7"].ToString();
                    if (MultiImg.Rows[0]["img1"].ToString().Length > 0)
                    {
                        listImg += MultiImg.Rows[0]["img1"].ToString() + "@";
                    }
                    if (MultiImg.Rows[0]["img2"].ToString().Length > 0)
                    {
                        listImg += MultiImg.Rows[0]["img2"].ToString() + "@";
                    }
                    if (MultiImg.Rows[0]["img3"].ToString().Length > 0)
                    {
                        listImg += MultiImg.Rows[0]["img3"].ToString() + "@";
                    }
                    if (MultiImg.Rows[0]["img4"].ToString().Length > 0)
                    {
                        listImg += MultiImg.Rows[0]["img4"].ToString() + "@";
                    }
                    if (MultiImg.Rows[0]["img5"].ToString().Length > 0)
                    {
                        listImg += MultiImg.Rows[0]["img5"].ToString() + "@";
                    }
                    if (listImg.Length > 0)
                    {
                        seeMore     = "<div id='LinkShow' style='text-align:center;'><a href='#LinkShow' onclick='OpenDivMulti(1);'><img src='image/common/seemore.gif' border='0'/></a></div>";
                        divseeMore  = "<div id='divShowMore' style='text-align:center;display:none'>";
                        divseeMore += "<object width='562' height='370'><embed src='image/common/ShowImg.swf?vl=" + listImg + "' wmode='transparent' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' width='562' height='370'></embed></object>";
                        divseeMore += "<div style='width:100px' class='text_title' onclick='OpenDivMulti(0);'><a href='#'>Đóng lại</a></div>";
                        divseeMore += "</div>";
                    }
                    //Test width file Img:
                    if (imgAd.Length > 0)
                    {
                        try
                        {
                            string path = Server.MapPath("image/multiimg/" + imgAd);
                            System.Drawing.Image CheckSize = System.Drawing.Image.FromFile(path);
                            if (CheckSize != null)
                            {
                                if (CheckSize.PhysicalDimension.Width > 562)
                                {
                                    imgAd = "<img src='image/multiimg/" + imgAd + "' border='0' width='562'/>";
                                }
                                else
                                {
                                    imgAd = "<img src='image/multiimg/" + imgAd + "' border='0'/>";
                                }
                            }
                        }
                        catch
                        {
                            imgAd = "";
                        }
                    }
                }
                strpro += "<tr><td colspan='3' height='5'></td></tr><tr>";
                strpro += "<td valign='top' width='195'>";
                strpro += "<img width='190' height='162' src='" + strurl + "'/>";
                strpro += seeMore + "</td>";
                strpro += "<td valign='top'><table border='0' width='100%' cellpadding='0' cellspacing='0'>";
                strpro += "<tr><td width='70'>" + tname + ":</td><td class='text_title'>" + strname + "</td></tr>";
                strpro += "<tr><td colspan='2' class='bg_line2'></td></tr>";
                strpro += "<tr><td>" + tbrand + ":</td><td class='text_title'><a href='default.html?menu=pro&brand=" + stridbrand + "' onmouseover='OnMOMenu(" + stridbrand + ",0,10,event);' onmouseout='TimeHidden();'>" + strBrand + "</a></td></tr>";
                strpro += "<tr><td colspan='2' class='bg_line2'></td></tr>";

                if (strprice.Equals("0"))
                {
                    strpro += "<tr><td>" + tprice + ":</td><td class='price'>" + tupdate + "</td></tr>";
                }
                else
                {
                    if (unitPrice.Equals("$"))
                    {
                        strpro += "<tr><td>" + tprice + ":</td><td class='price'>" + strprice + " VND (" + price2 + ") <span class='tvat'>" + strMVAT + "</span></td></tr>";
                    }
                    else if (unitPrice.Equals("$$"))
                    {
                        strpro += "<tr><td>" + tprice + ":</td><td class='price'>" + strprice + " VND (" + price2 + " USD) <span class='tvat'>" + strMVAT + "</span></td></tr>";
                    }
                    else
                    {
                        strpro += "<tr><td>" + tprice + ":</td><td class='price'>" + strprice + " " + unitPrice + " <span class='tvat'>" + strMVAT + "</span></td></tr>";
                    }
                }
                strpro += "<tr><td colspan='2' class='bg_line2'></td></tr>";
                strpro += "<tr><td>" + twarranty + ":</td><td class='price'>" + strwarranty + " " + tmonth + "</td></tr>";
                strpro += "<tr><td colspan='3' class='bg_line2'></td></tr>";
                if (viewpro.Rows.Count > 0)
                {
                    DateTime time = new DateTime();
                    time    = (DateTime)viewpro.Rows[0]["date"];
                    strpro += "<tr><td>" + tnview + ":</td><td><span style='color:red'>" + viewpro.Rows[0]["view"].ToString() + "</span> (" + time.ToString("dd/MM/yyyy") + ")</td></tr>";
                    strpro += "<tr><td colspan='3' class='bg_line2'></td></tr>";
                }
                int numAdress = add.Rows.Count;
                if (numAdress > 0)
                {
                    string   strAdd       = "";
                    string   DisContinued = "";
                    DateTime time         = new DateTime();
                    for (int i = 0; i < numAdress; i++)
                    {
                        int idstate = int.Parse(add.Rows[i]["id"].ToString());
                        if (idstate <= 5)
                        {
                            strAdd += "&raquo; " + add.Rows[i]["address"].ToString() + " (Đang có hàng)<br />";
                        }
                        else
                        {
                            time = DateTime.Now.ToUniversalTime();
                            time = time.AddHours(7);
                            if (idstate == 6)
                            {
                                time = time.AddHours(24);
                            }
                            else if (idstate == 7)
                            {
                                time = time.AddHours(24);
                            }
                            else if (idstate == 8)
                            {
                                time = time.AddHours(48);
                            }
                            else if (idstate == 9)
                            {
                                DisContinued = add.Rows[i]["DisContinued"].ToString();
                                if (DisContinued.Equals("7"))
                                {
                                    time    = (DateTime)add.Rows[i]["FirstImportDate"];
                                    strAdd += "&raquo; " + add.Rows[i]["address"].ToString() + " (Đợt hàng mới sẽ có ngày <font color='red'>" + time.ToString("dd/MM/yy") + "</font>)<br />";
                                    continue;
                                }
                                else
                                {
                                    time = time.AddHours(72);
                                }
                            }
                            else
                            {
                                continue;
                            }
                            strAdd += "&raquo; " + add.Rows[i]["address"].ToString() + " (Sẽ có thêm hàng ngày <font color='red'>" + time.ToString("dd/MM/yy") + "</font>)<br />";
                        }
                    }
                    strpro += "<tr><td class='price1'>" + twhere + ":</td><td colspan='2' class='text_2'>" + strAdd + "</td></tr>";
                }
                else
                {
                    strpro += "<tr><td>" + tstate + ":</td><td class='price' colspan='2'>" + tnothave + "</td></tr>";
                }
                strpro += "<tr><td colspan='3' class='bg_line2'></td></tr>";
                strpro += "<tr><td colspan='3' height='30' align='center'><input type='button' class='button3' value='" + tback + "' onclick='back();'/><input type='button' class='button3' value='" + tcompare + "' onclick='gocomp(" + strid + ")'/><input type='button' class='button3' value='" + torder + "' onclick='AddCart(" + strid + ",1);'/></td></tr>";
                strpro += "<tr><td height='4'></td></tr></table></td>";
                strpro += "</tr></table>";
                strpro += divseeMore;
                if (imgAd.Length > 0)
                {
                    strpro += "<div style='text-align:center;'>" + imgAd + "</div>";
                    strpro += "<div style='height:7px'></div>";
                }
                if (promotion.Rows.Count > 0)
                {
                    strpro += "<table border='0' cellpadding='0' cellspacing='0' width='100%' bgcolor='#FFF1EA'>";
                    strpro += "<tr><td class='title_1' align='center'>Sản phẩm đi kèm theo máy</td></tr>";
                    strpro += "<tr><td class='tavt'>";
                    try
                    {
                        //DateTime time = (DateTime)promotion.Rows[0]["StartDate"];
                        //strpro += "Từ ngày(Start): <span class='price'>" + time.ToString("dd/MM/yyyy") + "</span>";
                        //time = (DateTime)promotion.Rows[0]["EndDate"];
                        //strpro += ", Đến ngày(End): <span class='price'>" + time.ToString("dd/MM/yyyy") + "</span><br />";
                    }
                    catch
                    { }
                    strpro += promotion.Rows[0]["Note"].ToString() + "</td></tr>";
                    if (promotion.Rows[0]["UrlImage"].ToString().Length > 0)
                    {
                        strpro += "<tr><td align='center'><img class='imgpms' src='image/img_promotion/" + promotion.Rows[0]["UrlImage"].ToString() + "'/></td></tr>";
                        //strpro += "<tr><td align='center'><img class='imgpms' src='image/img_promotion/promotion_13_1282010104418.jpg'/></td></tr>";
                        strpro += "<tr><td align='center'>(Ảnh sản phẩm đi kèm theo máy)</td></tr>";
                    }
                    strpro += "<tr><td height='7'></td></tr>";
                    strpro += "</table>";
                }
                if (strnote.Length > 0)
                {
                    strpro += "<div class='title_1'>" + tdes + "</div>";
                    strpro += "<div class='tdes'>" + strnote + "<br />" + strdes + "</div><br />";
                }
            }
        }
        catch { }
    }
Example #42
0
    private string saveImage()
    {
        string ret      = string.Empty;
        string filename = string.Empty;

        try
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];


                Dictionary <string, object> parameters = new System.Collections.Generic.Dictionary <string, object>();
                parameters.Add("idUser", HttpContext.Current.Session["findOut"].ToString());
                string carpeta = string.Empty;
                //revisar en BD si el cliente tiene carpeta

                carpeta = DataAccess.executeStoreProcedureString("spr_Get_InfoLogo", parameters);

                //ver si tiene carpeta
                if (!String.IsNullOrEmpty(carpeta))
                {
                    //buscar el directorio
                    string PathDocs         = ConfigurationManager.AppSettings["EmpresasFiles"];
                    string inicio           = HttpContext.Current.Server.MapPath(PathDocs);
                    string directorioFisico = inicio + carpeta + "\\products\\" + Request.Form["idProduct"];
                    //string directorioVirtual = ConfigurationManager.AppSettings["EmpresasFiles"];
                    //string extension = System.IO.Path.GetExtension(Request.Files[0].FileName);

                    filename = file.FileName;

                    Common.makeDirectoryIfNotExists(directorioFisico);
                    //si existe, borra el que habia
                    if (System.IO.File.Exists(directorioFisico + "\\" + filename))
                    {
                        File.Delete(directorioFisico + "\\" + filename);
                    }

                    if (System.IO.File.Exists(directorioFisico + "\\small_" + filename))
                    {
                        File.Delete(directorioFisico + "\\small_" + filename);
                    }

                    //cambiar tamaño
                    System.Drawing.Image originalImage =
                        System.Drawing.Image.FromStream(file.InputStream, true, true);
                    //logo grande
                    System.Drawing.Image resizedImage = originalImage.GetThumbnailImage(160, 160, null, IntPtr.Zero);
                    //logo chico
                    System.Drawing.Image resizedImageCh = originalImage.GetThumbnailImage(50, 50, null, IntPtr.Zero);

                    //guarda el nuevo
                    //Request.Files[0].SaveAs(Server.MapPath(directorioVirtual) + carpeta + "\\logo.png" );
                    resizedImage.Save(directorioFisico + "\\" + filename);
                    resizedImageCh.Save(directorioFisico + "\\small_" + filename);

                    parameters.Clear();
                    parameters.Add("idUser", HttpContext.Current.Session["findOut"].ToString());
                    parameters.Add("idProducto", Request.Form["idProduct"]);
                    parameters.Add("idImagen", Request.Form["idImage"]);
                    parameters.Add("nombreArchivo", filename);
                    int result = 0;
                    try
                    {
                        result = DataAccess.executeStoreProcedureGetInt("Spr_insert_image", parameters);
                    }
                    catch (Exception ex)
                    {
                    }
                    if (result > 0)
                    {
                        ret = "{\"success\": true, \"message\": \"\", \"attr\": {\"idImage\": " + result + " , \"fileName\": \"" +
                              filename + "\"}}";
                    }
                    else
                    {
                        ret = "{\"success\": false, \"message\": \"Error al guardar los datos\"}";
                    }
                }
            }

            /*ret = "{\"success\": true, \"message\": \"\", \"attr\": {\"idProductImage\": " + 56 + " , \"name\": \"" +
             *    filename + "\"}}";*/
        }
        catch (Exception ex)
        {
            ret = "{\"success\": false, \"message\": \"" + ex.Message + "\"}";
        }

        return(ret);
    }
Example #43
0
    protected void btnInsertPic_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.Files.Count > 0 && txtProcedureSectionDetails.ActiveMode == AjaxControlToolkit.HTMLEditor.ActiveModeType.Design)
            {
                //string sPath = Server.MapPath("/" + ConfigurationManager.AppSettings["QMSDBPath"] + "/");


                try
                {
                    int Max_Height = 400;
                    //int Max_Width = 400;

                    System.Text.StringBuilder size = new System.Text.StringBuilder();

                    //string sPath = Server.MapPath("/" + ConfigurationManager.AppSettings["FAQAttachmentPath"] + "/");
                    string sPath = Server.MapPath("~/") + "Uploads\\FAQ\\";
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFile postedFile   = Request.Files[i];
                        string         FileName     = "FAQ_" + Guid.NewGuid().ToString() + Path.GetExtension(postedFile.FileName);
                        string         FullFilename = Path.Combine(sPath, FileName);
                        hdnAttacment_Id.Value = Convert.ToString(FileName);
                        postedFile.SaveAs(FullFilename);

                        ////BLL_LMS_FAQ.Faq_List_Attachment (Convert.ToInt32(Session["AttLoadId"]), FileName, Convert.ToInt32(Session["userid"]));
                        //DataTable dt_FAQ_Attachments = (DataTable)Session["dt_FAQ_Attachments"];
                        //DataRow dr = dt_FAQ_Attachments.NewRow();
                        //dr["Attachment_Name"] = FileName;
                        //dt_FAQ_Attachments.Rows.Add(dr);
                        //Session["dt_FAQ_Attachments"] = dt_FAQ_Attachments;

                        if (postedFile.ContentLength > 0)
                        {
                            if (!string.IsNullOrWhiteSpace(postedFile.FileName))
                            {
                                System.Drawing.Image objUpdImg = System.Drawing.Image.FromFile(Path.Combine(sPath, FileName));

                                if (objUpdImg.Height > Max_Height)
                                {
                                    size.Append("height:" + Max_Height.ToString() + "px;");
                                }

                                //if (objUpdImg.Width > Max_Width)
                                //    size.Append("width:" + Max_Width.ToString() + "px;");
                                //txtProcedureSectionDetails.Content += "<img style='" + size.ToString() + "'  src='/" + ConfigurationManager.AppSettings["FAQAttachmentPath"] + "/" + FileName + "'>";
                                //txtProcedureSectionDetails.Content += "<P><img style='" + size.ToString() + "'  src='" + "" + System.Configuration.ConfigurationManager.AppSettings["APP_URL"].ToString() + "Uploads/FAQ" + "/" + FileName + "'></P>";
                                txtProcedureSectionDetails.Content += "<P><img style='" + size.ToString() + "'  src='" + "../Uploads/FAQ" + "/" + FileName + "'></P>";
                                size.Clear();
                                //Session.Clear();
                            }
                        }
                    }
                }
                catch { }
                finally
                {
                    //updInserImage.Update();
                    Session["UploadedFiles_Name"] = "";
                }
            }
            else
            {
                //ucError.Text = Request.Files.Count > 0 ? "You are not in design mode" : "No Picture selected.";
                //ucError.Visible = true;
            }
        }
        catch (Exception ex)
        {
            //ucError.ErrorMessage = ex.Message;
            //ucError.Visible = true;
        }
    }
Example #44
0
    // Main function
    private void GenerateThumbnails()
    {
        while (true)
        {
            if (GenerateNewThumbnails)
            {
                m_bGenerationCompleted = false;

                lock (_ThumbnailsFiles)
                {
                    // Add a button for each file
                    for (int i = 0; i < _ThumbnailsFiles.Length; i++)
                    {
                        if (_ThumbnailsFiles[i].Extension.ToLower() == ".png" ||
                            _ThumbnailsFiles[i].Extension.ToLower() == ".jpg" ||
                            _ThumbnailsFiles[i].Extension.ToLower() == ".jpeg" ||
                            _ThumbnailsFiles[i].Extension.ToLower() == ".gif" ||
                            _ThumbnailsFiles[i].Extension.ToLower() == ".bmp")
                        {
                            ThumbData _data = new ThumbData();
                            _data._fullName = _ThumbnailsFiles[i].FullName;
                            _data._name     = _ThumbnailsFiles[i].Name;

                            try
                            {
                                System.Drawing.Image image = System.Drawing.Image.FromFile(_data._fullName);
                                System.Drawing.Image thumb = image.GetThumbnailImage(ThumbSize, ThumbSize, () => false, System.IntPtr.Zero);

                                _data._bytes = imageToByteArray(thumb);

                                if (image.Width == image.Height)
                                {
                                    _data.SizeX = ThumbSize;
                                    _data.SizeY = ThumbSize;
                                }
                                else if (image.Width > image.Height)
                                {
                                    _data.SizeX = ThumbSize;
                                    _data.SizeY = ThumbSize * ((float)image.Height / (float)image.Width);
                                }
                                else if (image.Width < image.Height)
                                {
                                    _data.SizeX = ThumbSize * ((float)image.Width / (float)image.Height);
                                    _data.SizeY = ThumbSize;
                                }

                                thumb.Dispose();
                                image.Dispose();
                            }
                            catch (System.ArgumentException e)
                            {
                                Debug.LogError("ArgumentException when generating thumbnail " + i + ".\n\n" + e.Message);
                            }
                            catch (System.IO.FileNotFoundException e)
                            {
                                Debug.LogError("FileNotFoundException when generating thumbnail " + i + ".\n\n" + e.Message);
                            }
                            catch (System.OutOfMemoryException e)
                            {
                                Debug.LogError("OutOfMemoryException when generating thumbnail " + i + ".\n\n" + e.Message);
                            }
                            catch
                            {
                                Debug.LogError("Unknow error when generating thumbnail " + i + ".\n\n");
                            }

                            lock (m_pImagesBytesArray)
                            {
                                m_pImagesBytesArray.Add(_data);
                            }

                            if (CancelThread || CancelGeneration)
                            {
                                break;
                            }
                        }
                    }
                }

                m_bGenerationCompleted = true;
                GenerateNewThumbnails  = false;
            }

            if (CancelThread)
            {
                CancelThread = false;
                break;
            }

            if (CancelGeneration)
            {
                m_bGenerationCompleted = true;
                GenerateNewThumbnails  = false;
                lock (m_pImagesBytesArray)
                {
                    m_pImagesBytesArray.Clear();
                }

                lock (_ThumbnailsFiles)
                {
                    _ThumbnailsFiles = new FileInfo[0];
                }
                CancelGeneration = false;
            }

            Thread.Sleep(100);
        }
    }
Example #45
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Drawing.Image original_image = null;
        String fileNameInfo       = String.Empty;
        String tempPath           = String.Empty;
        bool   directoryNotExists = false;

        try
        {
            if (String.IsNullOrEmpty(UploadControl))
            {
                Response.End();
            }
            // Get the data
            HttpPostedFile image_upload = Request.Files["Filedata"];
            fileNameInfo = Path.GetFileName(image_upload.FileName);
            tempPath     = Server.MapPath("../../" + PathDestination);
            if (Directory.Exists(tempPath))
            {
                image_upload.SaveAs(tempPath + fileNameInfo);
                Response.StatusCode = 200;
                Response.Write("Success");
            }
            else
            {
                directoryNotExists = true;
                Response.End();
            }
        }
        catch
        {
            if (String.IsNullOrEmpty(UploadControl))
            {
                Response.StatusCode = 601;
                Response.Write("Can't use this page alone.");
            }
            else
            {
                if (directoryNotExists)
                {
                    Response.StatusCode = 600;
                    Response.Write("Directory Not Exists");
                }
                else
                {
                    Response.StatusCode = 500;
                    Response.Write("An error occured");
                }

                //if ((ex.Message.Length > 30) && (ex.Message.Substring( 0, 34 ) == "The process cannot access the file") && (ex.Message.Substring( ex.Message.Length - 44 ) == "because it is being used by another process."))
                //{
                //    Response.StatusCode = 602;
                //    Response.Write( ex.Message.Substring( 0, 34 ) + " " + ex.Message.Substring( ex.Message.Length - 44 ) );
                //}
            }
            // If any kind of error occurs return a 500 Internal Server error
            Response.End();
        }
        finally
        {
            // Clean up
            if (original_image != null)
            {
                original_image.Dispose();
            }
            Response.End();
        }
    }
 private void toBarCode(String text)
 {
     System.Drawing.Image myimage = Code128Rendering.MakeBarcodeImage(text, 1, true);
     myimage.Save(Server.MapPath("~/images/sample.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
     img_BarCode.ImageUrl = "~/images/sample.jpg";
 }
    protected void btnEnviar_Click(object sender, EventArgs e)
    {
        hdf.Value = Session["value"].ToString();

        DataSet ds = mot_motoristaDB.SelectID(Convert.ToInt32(hdf.Value));

        mot_motorista mot = new mot_motorista();

        mot.Mot_id = Convert.ToInt32(ds.Tables[0].Rows[0]["mot_id"]);

        tpc_tipo_contato tpc = new tpc_tipo_contato();

        tpc.Tpc_id = Convert.ToInt32(ddl.SelectedValue);


        mxc_motorista_tipo_contato mxc = new mxc_motorista_tipo_contato();

        if (ddl.SelectedIndex == 1)
        {
            mxc.Mxc_descricao = txtTelefone.Text;
        }
        else if (ddl.SelectedIndex == 2)
        {
            mxc.Mxc_descricao = txtCelular.Text;
        }
        else if (ddl.SelectedIndex == 3)
        {
            mxc.Mxc_descricao = txtWhatsapp.Text;
        }
        else if (ddl.SelectedIndex == 4)
        {
            mxc.Mxc_descricao = txtEmailAlt.Text;
        }

        mxc.Mot_id = mot;
        mxc.Tpc_id = tpc;
        mxc_motorista_tipo_contatoDB.Insert(mxc);

        string dir = Request.PhysicalApplicationPath + "pg\\uploads\\";

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }

        foreach (HttpPostedFile flp in fup.PostedFiles)
        {
            double mp = 2000;

            if (fup.HasFile)
            {
                string arq = Path.GetFileName(flp.FileName);
                string ext = Path.GetExtension(flp.FileName);
                ext = ext.ToLower();
                double ta = flp.ContentLength / 1024;

                if (ext == ".jpg" || ext == ".png" || ext == ".gif")
                {
                    if (ta <= mp)
                    {
                        arq = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ext;
                        if (!File.Exists(dir + arq))
                        {
                            flp.SaveAs(dir + arq);

                            System.Drawing.Image imgOriginal = System.Drawing.Image.FromFile(Server.MapPath("~/pg/uploads/" + arq), true);

                            System.Drawing.Image.GetThumbnailImageAbort miniatura = new System.Drawing.Image.GetThumbnailImageAbort(erro);

                            System.Drawing.Image imgRedimensionada;

                            int width, height;

                            if (imgOriginal.Width > 200)
                            {
                                width = 200; height = (int)(width * imgOriginal.Height) / imgOriginal.Width;
                            }
                            else
                            {
                                width = imgOriginal.Width; height = imgOriginal.Height;
                            }

                            imgRedimensionada = imgOriginal.GetThumbnailImage(width, height, miniatura, IntPtr.Zero);


                            imgRedimensionada.Dispose();

                            imgOriginal.Dispose();

                            //Atualizar tipo de conta
                            if (rbMensal.Checked)
                            {
                                string        kindOfPremium = "Premium M";
                                DataSet       dsp           = new DataSet();
                                tip_tipoconta tip           = new tip_tipoconta();

                                dsp        = tip_tipocontaDB.SelectID(kindOfPremium);
                                tip.Tip_id = Convert.ToInt32(dsp.Tables[0].Rows[0][0]);
                                mot.Tip_id = tip;
                                mot_motoristaDB.UpdatePremium(mot);
                            }
                            else if (rbAnual.Checked)
                            {
                                string        kindOfPremium = "Premium A";
                                DataSet       dsp           = new DataSet();
                                tip_tipoconta tip           = new tip_tipoconta();

                                dsp        = tip_tipocontaDB.SelectID(kindOfPremium);
                                tip.Tip_id = Convert.ToInt32(dsp.Tables[0].Rows[0][0]);
                                mot.Tip_id = tip;
                                mot_motoristaDB.UpdatePremium(mot);
                            }

                            //Response.Write("<script>alert('Cadastrado com sucesso');</script>");
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalS();", true);
                            tdo_tipodocumento tdo = new tdo_tipodocumento();
                            tdo.Tdo_image = arq;
                            tdo_tipodocumentoDB.Insert(tdo);

                            string  img = arq;
                            DataSet id  = new DataSet();
                            id         = tdo_tipodocumentoDB.SelectImage(img);
                            tdo.Tdo_id = Convert.ToInt32(id.Tables[0].Rows[0][0]);

                            doc_documento doc = new doc_documento();
                            doc.Mot_id = mot;
                            doc.Tdo_id = tdo;
                            doc_documentoDB.Insert(doc);

                            pBefore.Visible = false;
                            pAfter.Visible  = true;
                        }
                        else
                        {
                            //Response.Write("<script>alert('Arquivo ja existe');</script>");
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalF();", true);
                        }
                    }
                    else
                    {
                        //Response.Write("<script>alert('Tamanho maximo excedido - 500KB');</script>");
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalMS();", true);
                    }
                }
                else
                {
                    //Response.Write("<script>alert('Extensão invalida');</script>");
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalEI();", true);
                }
            }
            else
            {
                //Response.Write("<script>alert('Selecione um arquivo');</script>");
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalSl();", true);
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            UserProfileInfo objinfo     = new UserProfileInfo();
            string          filename    = "";
            string          thumbTarget = Server.MapPath("~/Modules/Admin/UserManagement/UserPic");
            if (!Directory.Exists(thumbTarget))
            {
                Directory.CreateDirectory(thumbTarget);
            }
            System.Drawing.Image.GetThumbnailImageAbort thumbnailImageAbortDelegate = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            if (fuImage.HasFile)
            {
                string   fName = fuImage.PostedFile.FileName;
                FileInfo fi    = new FileInfo(fName);
                fName = Path.GetFileName(fName);
                string ext = fi.Extension.ToLower();
                if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
                {
                    double fs = fuImage.PostedFile.ContentLength / (1024 * 1024);
                    if (fs > 3)
                    {
                        ShowHideProfile();
                        ShowMessage("", GetSageMessage("UserManagement", "ImageTooLarge"), "", SageMessageType.Alert);
                        return;
                    }
                    else
                    {
                        Random ran  = new Random();
                        int    rand = ran.Next(1111111, 9999999);
                        if (!File.Exists(Server.MapPath("~/Modules/Admin/UserManagement/UserPic/" + fName)))
                        {
                            string fullfileName = Path.GetFileNameWithoutExtension(fName) + rand + ext;

                            imgUser.ImageUrl = "~/Modules/Admin/UserManagement/UserPic/" + fullfileName;
                            using (System.Drawing.Bitmap originalImage
                                       = new System.Drawing.Bitmap(fuImage.PostedFile.InputStream))
                            {
                                using (System.Drawing.Image thumbnail
                                           = originalImage.GetThumbnailImage(500, 500, thumbnailImageAbortDelegate, IntPtr.Zero))
                                {
                                    thumbnail.Save(System.IO.Path.Combine(thumbTarget, fullfileName));
                                }
                            }
                            filename = fullfileName;
                        }
                    }
                }
                else
                {
                    {
                        ShowHideProfile();
                        ShowMessage("", GetSageMessage("UserManagement", "InvalidImageFormat"), "", SageMessageType.Error);
                        return;
                    }
                }
            }

            if (filename == "")
            {
                if (Session[SessionKeys.SageFrame_UserProfilePic] != null)
                {
                    filename = Session[SessionKeys.SageFrame_UserProfilePic].ToString();
                }
                btnDeleteProfilePic.Visible = false;
            }
            else
            {
                btnDeleteProfilePic.Visible = true;
            }
            objinfo.Image     = filename;
            objinfo.UserName  = GetUsername;
            objinfo.FirstName = txtFName.Text;
            objinfo.LastName  = txtLName.Text;
            objinfo.FullName  = txtFullName.Text;
            objinfo.Location  = txtLocation.Text;
            objinfo.AboutYou  = txtAboutYou.Text;
            //objinfo.Email = txtEmail1.Text + (txtEmail2.Text != "" ? "," + txtEmail2.Text : "") + (txtEmail3.Text != "" ? ',' + txtEmail3.Text : "");
            objinfo.Email       = txtEmail1.Text;
            objinfo.ResPhone    = txtResPhone.Text;
            objinfo.MobilePhone = txtMobile.Text;
            objinfo.Others      = txtOthers.Text;
            objinfo.AddedOn     = DateTimeHelper.GetUtcTime(DateTime.Now);
            objinfo.AddedBy     = GetUsername;
            objinfo.UpdatedOn   = DateTimeHelper.GetUtcTime(DateTime.Now);
            objinfo.PortalID    = GetPortalID;
            objinfo.UpdatedBy   = GetUsername;
            objinfo.BirthDate   = txtBirthDate.Text == string.Empty ? DateTimeHelper.GetUtcTime(falseDate) : DateTimeHelper.GetUtcTime(txtBirthDate.Text);
            objinfo.Gender      = rdbGender.SelectedIndex;
            UserProfileController.AddUpdateProfile(objinfo);
            Session.Remove(SessionKeys.SageFrame_UserProfilePic);
            ShowMessage("", GetSageMessage("UserManagement", "UserProfileSavedSuccessfully"), "", SageMessageType.Success);
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
Example #49
0
        private static void PrintPage(object o, PrintPageEventArgs e)
        {
            float height = 0;

            System.Drawing.Text.PrivateFontCollection privateFonts = new PrivateFontCollection();
            privateFonts.AddFontFile("Slike/msgothic.ttc");
            System.Drawing.Font font = new Font(privateFonts.Families[0], Convert.ToInt16(DTpostavke.Rows[0]["font_print_size"].ToString()));

            System.Drawing.Text.PrivateFontCollection privateFonts_ukupno = new PrivateFontCollection();
            privateFonts_ukupno.AddFontFile("Slike/msgothic.ttc");
            System.Drawing.Font font_ukupno = new Font(privateFonts.Families[0], Class.PosPrint.fontUkupnoSizeMailiPrinter);

            try
            {
                if (File.Exists("C://logo/logo.jpg"))
                {
                    Image ik         = Image.FromFile("C://logo/logo.jpg");
                    bool  bigerWidth = false;
                    float rezol      = 0;
                    if (ik.Size.Width > ik.Size.Height)
                    {
                        bigerWidth = true;
                        rezol      = ik.Size.Width / ik.Size.Height;
                    }
                    else
                    {
                        rezol = ik.Size.Height / ik.Size.Width;
                    }

                    int newWidth = ik.Size.Width, newHeight = ik.Size.Height;

                    if ((bigerWidth ? ik.Size.Width : ik.Size.Height) > e.PageSettings.PrintableArea.Size.Width)
                    {
                        if (bigerWidth)
                        {
                            newWidth  = (int)e.PageSettings.PrintableArea.Size.Width;
                            newHeight = (ik.Size.Height * newWidth) / ik.Size.Width;
                        }
                        else
                        {
                            newHeight = (int)e.PageSettings.PrintableArea.Size.Width;
                            newWidth  = (newHeight * ik.Size.Width) / ik.Size.Height;
                        }
                    }

                    Point pp = new Point(0, 0);
                    e.Graphics.DrawImage(ik, (e.PageSettings.PrintableArea.Size.Width - newWidth) / 2, height, newWidth, newHeight);
                    pageHeight = (int)(height + newHeight);

                    height = newHeight;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            //header
            string       drawString = _1;
            Font         drawFont   = font;
            SolidBrush   drawBrush  = new SolidBrush(Color.Black);
            StringFormat drawFormat = new StringFormat();

            e.Graphics.DrawString(drawString, drawFont, drawBrush, 0, height, drawFormat);
            SizeF stringSize = new SizeF();

            stringSize = e.Graphics.MeasureString(_1, drawFont);

            height = float.Parse(stringSize.Height.ToString()) + height;

            //stavke
            float y = 0, x = 0;

            if (_2.Contains("{[5AR]}") && Class.PosPrint.ispisUkupnoIspodStavkiMaliPrinter)
            {
                string[] _2s = _2.Split(new string[] { "{[5AR]}" + Environment.NewLine }, StringSplitOptions.None);

                drawString = _2s[0];
                drawFont   = font;
                y          = height;
                x          = 0.0F;
                drawFormat = new StringFormat();
                e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
                stringSize = e.Graphics.MeasureString(_2s[0], drawFont);

                height = float.Parse(stringSize.Height.ToString()) + height;

                //Ukupno
                //string s1 = "UKUPNO:";
                //string s2 = ukupno.ToString("#0.00") + " KN";
                string s3 = "";
                for (int i = 0; i < (RecLineChars - _3.Length - 5); i++)
                {
                    s3 += " ";
                }
                //_3 = s1 + s3 + s2;
                //_3 = _3.Split(':')[0] + s3 + _3.Split(':')[1];
                drawString = _3.ToUpper();
                drawFont   = font_ukupno;
                y          = height;
                x          = 0.0F;
                drawFormat = new StringFormat();
                e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
                stringSize = e.Graphics.MeasureString(_3, drawFont);

                height = float.Parse(stringSize.Height.ToString()) + height;

                drawString = _2s[1];
                drawFont   = font;
                y          = height;
                x          = 0.0F;
                drawFormat = new StringFormat();
                e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
                stringSize = e.Graphics.MeasureString(_2s[1], drawFont);

                height = float.Parse(stringSize.Height.ToString()) + height;
            }
            else
            {
                drawString = _2;
                drawFont   = font;
                y          = height;
                x          = 0.0F;
                drawFormat = new StringFormat();
                e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
                stringSize = e.Graphics.MeasureString(_2, drawFont);

                height = float.Parse(stringSize.Height.ToString()) + height;
            }

            //fiskal
            drawString = fiskal_tekst;
            drawFont   = new System.Drawing.Font("Arial", 9F);
            y          = height;
            x          = 0.0F;
            drawFormat = new StringFormat();
            e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
            stringSize = e.Graphics.MeasureString(fiskal_tekst, drawFont);

            height = float.Parse(stringSize.Height.ToString()) + height;

            //kockice
            drawString = kockice;
            drawFont   = font;
            y          = height;
            x          = 0.0F;
            drawFormat = new StringFormat();
            e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
            stringSize = e.Graphics.MeasureString(kockice, drawFont);

            height = float.Parse(stringSize.Height.ToString()) + height;

            if (!_2.Contains("{[5AR]}") && !Class.PosPrint.ispisUkupnoIspodStavkiMaliPrinter)
            {
                //Ukupno
                drawString = _3;
                drawFont   = font_ukupno;
                y          = height;
                x          = 0.0F;
                drawFormat = new StringFormat();
                e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
                stringSize = e.Graphics.MeasureString(_3, drawFont);

                height = float.Parse(stringSize.Height.ToString()) + height;
            }

            //Naša zahvala
            drawString = _4;
            drawFont   = font_ukupno;
            y          = height;
            x          = 0.0F;
            drawFormat = new StringFormat();
            e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
            stringSize = e.Graphics.MeasureString(_4, drawFont);

            height = float.Parse(stringSize.Height.ToString()) + height;

            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["aktivnost"].ToString() == "DA")
                {
                    //Barcode
                    if (img_barcode != null)
                    {
                        System.Drawing.Image img = img_barcode;
                        e.Graphics.DrawImage(img_barcode, 0, height, 250, 50);
                    }
                    height = height + 70;
                }
            }

            //Bottom
            drawString = _5;
            drawFont   = font;
            y          = height;
            x          = 0.0F;
            drawFormat = new StringFormat();
            e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);

            stringSize = e.Graphics.MeasureString(_5.TrimEnd(), drawFont);
            height     = float.Parse(stringSize.Height.ToString()) + height;

            try
            {
                if (File.Exists("C://logo/logo2.jpg"))
                {
                    Image ik         = Image.FromFile("C://logo/logo2.jpg");
                    bool  bigerWidth = false;
                    float rezol      = 0;
                    if (ik.Size.Width > ik.Size.Height)
                    {
                        bigerWidth = true;
                        rezol      = ik.Size.Width / ik.Size.Height;
                    }
                    else
                    {
                        rezol = ik.Size.Height / ik.Size.Width;
                    }

                    int newWidth = ik.Size.Width, newHeight = ik.Size.Height;

                    if ((bigerWidth ? ik.Size.Width : ik.Size.Height) > e.PageSettings.PrintableArea.Size.Width)
                    {
                        if (bigerWidth)
                        {
                            newWidth  = (int)e.PageSettings.PrintableArea.Size.Width;
                            newHeight = (ik.Size.Height * newWidth) / ik.Size.Width;
                        }
                        else
                        {
                            newHeight = (int)e.PageSettings.PrintableArea.Size.Width;
                            newWidth  = (newHeight * ik.Size.Width) / ik.Size.Height;
                        }
                    }

                    Point pp = new Point(0, 0);
                    e.Graphics.DrawImage(ik, (e.PageSettings.PrintableArea.Size.Width - newWidth) / 2, height, newWidth, newHeight);
                    pageHeight = (int)(height + newHeight);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            // Code-iT verzija
            drawString = _6;
            drawFont   = font;
            y          = height;
            x          = 0.0F;
            drawFormat = new StringFormat();
            e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);

            stringSize = e.Graphics.MeasureString(_6.TrimEnd(), drawFont);
            height     = float.Parse(stringSize.Height.ToString()) + height;

            pageHeight++;

            if (e.HasMorePages)
            {
                e.HasMorePages = false;
            }

            if (pageHeight > e.PageSettings.PaperSize.Height)
            {
                PaperSize psNew = new System.Drawing.Printing.PaperSize("Racun", e.PageSettings.PrinterSettings.DefaultPageSettings.PaperSize.Width, pageHeight);
                Size      sSize = new Size(psNew.Width, psNew.Height);

                e.PageSettings.PrinterSettings.DefaultPageSettings.PaperSize = psNew;
                e.PageSettings.PrinterSettings.DefaultPageSettings.Bounds.Inflate(sSize);
                e.PageSettings.PrinterSettings.DefaultPageSettings.PrintableArea.Inflate(sSize);
                e.PageSettings.PrinterSettings.DefaultPageSettings.PrinterSettings.DefaultPageSettings.PrintableArea.Inflate(sSize);

                e.PageSettings.PaperSize = psNew;

                e.PageSettings.Bounds.Inflate(sSize);

                e.PageBounds.Inflate(sSize);

                e.PageSettings.PrintableArea.Inflate(sSize);

                e.HasMorePages = true;
                e.Graphics.Clear(Color.White);
                e.Graphics.ResetClip();
                e.Graphics.Clip.MakeEmpty();
            }
        }
Example #50
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        // Read the file and convert it to Byte Array
        string filePath    = UploadImage.PostedFile.FileName;
        string filename    = Path.GetFileName(filePath);
        string ext         = Path.GetExtension(filename);
        string contenttype = String.Empty;

        //Set the contenttype based on File Extension
        switch (ext.ToLower())
        {
        case ".jpeg":
        case ".jpg":
            contenttype = "image/jpg";
            break;

        case ".png":
            contenttype = "image/png";
            break;

        case ".gif":
            contenttype = "image/gif";
            break;

        case ".bmp":
            contenttype = "image/bmp";
            break;
        }

        if (contenttype != String.Empty || string.IsNullOrEmpty(filename))
        {
            Stream       fs       = UploadImage.PostedFile.InputStream;
            BinaryReader br       = new BinaryReader(fs);
            Byte[]       bytes    = br.ReadBytes((Int32)fs.Length);
            Byte[]       newBytes = new byte[0];
            if (!string.IsNullOrEmpty(filename))
            {
                MemoryStream         ms          = new MemoryStream(bytes);
                System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
                MemoryStream         newMs       = new MemoryStream();

                ResizeImage(returnImage, 300).Save(newMs, System.Drawing.Imaging.ImageFormat.Jpeg);
                newBytes = newMs.ToArray();
            }
            //insert the file into database
            string strQuery = "insert into ExchangeDB..Item(UserId, ItemName, ItemDesc, ContentType, Image, Category)" +
                              " values (@UserId, @ItemName, @ItemDesc, @ContentType, @Image, @Category)";

            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@UserId", SqlDbType.Int).Value           = Convert.ToInt32(Session["UserId"].ToString());
            cmd.Parameters.Add("@ItemName", SqlDbType.NVarChar).Value    = ItemName.Text;
            cmd.Parameters.Add("@ItemDesc", SqlDbType.NVarChar).Value    = ItemDescription.Text;
            cmd.Parameters.Add("@ContentType", SqlDbType.NVarChar).Value = "image/jpg";
            cmd.Parameters.Add("@Image", SqlDbType.Binary).Value         = newBytes.Length > 0 ? newBytes : (object)DBNull.Value;
            cmd.Parameters.Add("@Category", SqlDbType.NVarChar).Value    = CategoryDropDown.SelectedValue;

            if (InsertUpdateData(cmd))
            {
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text      = "Item Uploaded Successfully";
                Response.Redirect("~/Home.aspx");
            }
        }
        else
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text      = "File format not recognised.";
        }
    }
Example #51
0
    /// <summary>
    /// 加缩略图同时加水印
    /// </summary>
    /// <param name="upFile"></param>
    /// <param name="_picWidth"></param>
    /// <param name="_picHeight"></param>
    /// <param name="fileSize"></param>
    /// <param name="filePath"></param>
    /// <param name="serverPath"></param>
    /// <returns></returns>
    private static string UpPhoto(FileUpload upFile, int _picWidth, int _picHeight, int fileSize, string filePath, string serverPath)
    {
        string strFullName      = upFile.PostedFile.FileName;
        string strWaterFullName = serverPath + waterImagePath;
        int    size             = upFile.PostedFile.ContentLength;
        int    j        = strFullName.LastIndexOf("\\") + 1;
        string fileName = strFullName.Substring(j);
        int    a        = fileName.LastIndexOf(".") + 1;
        string typeName = fileName.Substring(a).ToUpper();
        //让系统的时间作为图片的名称
        string name = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
                      System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Millisecond.ToString();
        //保存的文件路径和名称
        string picPath         = serverPath + "/" + filePath + name + ".jpg";
        string newPath         = "";
        string smallPicPath    = "";
        string picRelativePath = "";

        if (typeName == "GIF" || typeName == "JPG" || typeName == "PNG" || typeName == "BMP")
        {
            if (fileSize > size)
            {
                //先把文件提交到服务器
                upFile.SaveAs(picPath);
                smallPicPath = serverPath + "/" + filePath + "smallphoto/" + name + ".jpg";

                //对图片进行缩略
                double picWidth  = Convert.ToDouble(_picWidth);
                double picHeight = Convert.ToDouble(_picHeight);

                System.Drawing.Image im = System.Drawing.Image.FromStream(upFile.PostedFile.InputStream);
                double height           = Convert.ToDouble(im.Height);
                double width            = Convert.ToDouble(im.Width);
                int    suoluetuHeight   = 0;
                int    suoluetuWidth    = 0;
                double beishuHeight     = 1;
                double beishuWidth      = 1;
                if (height > picHeight)
                {
                    beishuHeight = height / picHeight;
                }
                else
                {
                    suoluetuHeight = Convert.ToInt16(height);
                }

                if (width > picWidth)
                {
                    beishuWidth = width / picWidth;
                }
                else
                {
                    suoluetuWidth = Convert.ToInt16(width);
                }

                if (height > width)
                {
                    suoluetuHeight = Convert.ToInt16(height / beishuHeight);
                    suoluetuWidth  = Convert.ToInt16(width / beishuHeight);
                }
                else
                {
                    suoluetuHeight = Convert.ToInt16(height / beishuWidth);
                    suoluetuWidth  = Convert.ToInt16(width / beishuWidth);
                }
                System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                Bitmap myBitmap = new Bitmap(picPath);

                System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(suoluetuWidth, suoluetuHeight, myCallback, IntPtr.Zero);
                //将图像保存到页面输出流中,并制定输出图像的格式

                myThumbnail.Save(smallPicPath, System.Drawing.Imaging.ImageFormat.Jpeg);

                myBitmap.Dispose();

                //首先给大图图片添加水印------------------------------------------------------------------------------

                //创建一个图像对象
                System.Drawing.Image image = System.Drawing.Image.FromFile(picPath);
                //水印图片
                System.Drawing.Image waterImage = System.Drawing.Image.FromFile(strWaterFullName);

                //Create   a   new   FrameDimension   object   from   this   image

                FrameDimension ImgFrmDim = new FrameDimension(image.FrameDimensionsList[0]);

                int nFrameCount = image.GetFrameCount(ImgFrmDim);

                //   Save   every   frame   into   jpeg   format

                for (int i = 0; i < nFrameCount; i++)
                {
                    image.SelectActiveFrame(ImgFrmDim, i);

                    image.Save(string.Format(serverPath + "/" + filePath + "Frame{0}.jpg ", i), ImageFormat.Jpeg);
                }
                image.Dispose();

                for (int i = 0; i < nFrameCount; i++)
                {
                    string pa = serverPath + "/" + filePath + "Frame" + i + ".jpg ";
                    System.Drawing.Image Image = System.Drawing.Image.FromFile(pa);
                    Graphics             g     = Graphics.FromImage(Image);
                    g.DrawImage(waterImage, new Rectangle(Image.Width - waterImage.Width, Image.Height - waterImage.Height, waterImage.Width, waterImage.Height), 0, 0, waterImage.Width, waterImage.Height, GraphicsUnit.Pixel);

                    g.Dispose();

                    newPath         = serverPath + "/" + filePath + name + i.ToString() + "." + "jpg ";
                    picRelativePath = filePath + name + i.ToString() + "." + "jpg ";
                    Image.Save(newPath);
                    Image.Dispose();

                    if (File.Exists(pa))
                    {
                        File.Delete(pa);
                    }
                }
                if (File.Exists(picPath))
                {
                    File.Delete(picPath);
                }

                //然后给小图加水印----------------------------------------------------------------------------------
                strWaterFullName = serverPath + waterImagePath;
                System.Drawing.Image smallimage = System.Drawing.Image.FromFile(smallPicPath);

                //水印图片
                System.Drawing.Image smallwaterImage = System.Drawing.Image.FromFile(strWaterFullName);

                //Create   a   new   FrameDimension   object   from   this   image

                FrameDimension ImgFrmDimSmall = new FrameDimension(smallimage.FrameDimensionsList[0]);

                nFrameCount = smallimage.GetFrameCount(ImgFrmDimSmall);

                //   Save   every   frame   into   jpeg   format

                for (int i = 0; i < nFrameCount; i++)
                {
                    smallimage.SelectActiveFrame(ImgFrmDimSmall, i);

                    smallimage.Save(string.Format(serverPath + "/" + filePath + "smallphoto/" + "Frame{0}.jpg ", i), ImageFormat.Jpeg);
                }
                smallimage.Dispose();

                for (int i = 0; i < nFrameCount; i++)
                {
                    string pa = serverPath + "/" + filePath + "smallphoto/" + "Frame" + i + ".jpg ";
                    System.Drawing.Image Image = System.Drawing.Image.FromFile(pa);
                    Graphics             g     = Graphics.FromImage(Image);
                    g.DrawImage(smallwaterImage, new Rectangle(Image.Width - smallwaterImage.Width, Image.Height - smallwaterImage.Height, smallwaterImage.Width, smallwaterImage.Height), 0, 0, smallwaterImage.Width, smallwaterImage.Height, GraphicsUnit.Pixel);

                    g.Dispose();

                    newPath = serverPath + "/" + filePath + "smallphoto/" + name + i.ToString() + "." + "jpg ";
                    Image.Save(newPath);
                    Image.Dispose();

                    if (File.Exists(pa))
                    {
                        File.Delete(pa);
                    }
                }

                if (File.Exists(smallPicPath))
                {
                    File.Delete(smallPicPath);
                }
            }
        }
        return(picRelativePath);
    }
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void imgBtnLoad_Click(object sender, ImageClickEventArgs e)
    {
        if (!fulPhoto.HasFile)
        {
            lbMessage.Text = "请选择上传图片!";
            return;
        }
        else
        {
            try
            {
                //获取上传文件路径
                string filePath = fulPhoto.PostedFile.FileName;
                //获取上传文件后缀
                string fileExt = filePath.Substring(filePath.LastIndexOf(".") + 1);
                //限定上传格式
                if (fileExt.ToLower() == "gif" || fileExt.ToLower() == "jpg" || fileExt.ToLower() == "bmp" || fileExt.ToLower() == "png")
                {
                    if (fulPhoto.PostedFile.ContentLength > 5120000)
                    {
                        lbMessage.Text = "限定上传图片的大小不能超出5M!";
                        return;
                    }
                    else
                    {
                        //根据时间生成文件名
                        string nowTime  = Album.CreateDateTimeString();
                        string fileName = nowTime + "." + fileExt;
                        //源文件保存路径
                        string savePath = Server.MapPath("UpFile/");
                        //缩略图保存路径
                        string imgPath = Server.MapPath("UpSmall/");
                        //上传图片
                        fulPhoto.PostedFile.SaveAs(savePath + fileName);

                        //创建自定义Album类对象实例
                        Album am = new Album();
                        //根据图片的s宽、高比例生成缩略图
                        System.Drawing.Image img = System.Drawing.Image.FromFile(savePath + fileName);
                        if (img.Width >= img.Height)
                        {
                            am.GetThumbnail(savePath + fileName, imgPath + fileName, 400, 300, "Cut");
                        }
                        else
                        {
                            am.GetThumbnail(savePath + fileName, imgPath + fileName, 320, 350, "Cut");
                        }


                        //文件类型
                        string p_type = fulPhoto.PostedFile.ContentType;
                        //文件大小
                        int p_size     = fulPhoto.PostedFile.ContentLength;
                        int categoryId = Convert.ToInt32(ddlCategory.SelectedValue);
                        //调用类方法将数据插入到数据库
                        int result = am.AddPhoto(tbName.Text.Trim(), tbDescript.Text.Trim(), fileName, p_type, p_size, categoryId);
                        Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('图片上传成功!');location.href='Photo_load.aspx';</script>");
                    }
                }
                else
                {
                    lbMessage.Text = "只允许上传gif,jpg,bmp,png格式的图片文件!";
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }
Example #53
0
    /// <summary>
    /// 上传加水印图片
    /// </summary>
    /// <param name="upFile"></param>
    /// <param name="fileSize"></param>
    /// <param name="filePaht"></param>
    /// <param name="serverPath"></param>
    /// <returns></returns>
    private static string UploadAddWaterImage(FileUpload upFile, int fileSize, string filePath, string serverPath)
    {
        string strFullName      = upFile.PostedFile.FileName;
        string strWaterFullName = serverPath + waterImagePath;
        int    size             = upFile.PostedFile.ContentLength;
        int    j        = strFullName.LastIndexOf("\\") + 1;
        string fileName = strFullName.Substring(j);
        int    a        = fileName.LastIndexOf(".") + 1;
        string typeName = fileName.Substring(a).ToUpper();
        //让系统的时间作为图片的名称
        string name = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
                      System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Millisecond.ToString();
        //保存的文件路径和名称
        string picPath         = serverPath + "/" + filePath + name + ".jpg";
        string newPath         = "";
        string picRelativePath = "";

        if (typeName == "GIF" || typeName == "JPG" || typeName == "PNG" || typeName == "BMP")
        {
            if (fileSize > size)
            {
                //先把文件提交到服务器
                upFile.SaveAs(picPath);

                //加文字水印,注意,这里的代码和以下加图片水印的代码不能共存
                //System.Drawing.Image image = System.Drawing.Image.FromFile(path);
                //Graphics g = Graphics.FromImage(image);
                //g.DrawImage(image, 0, 0, image.Width, image.Height);
                //Font f = new Font("Verdana", 32);
                //Brush b = new SolidBrush(Color.White);
                //string addText = AddText.Value.Trim();
                //g.DrawString(addText, f, b, 10, 10);
                //g.Dispose();

                //首先给图片添加水印

                System.Drawing.Image.GetThumbnailImageAbort myCallback =
                    new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

                //创建一个图像对象
                //Bitmap bmp = new Bitmap(picPath);

                System.Drawing.Image image = System.Drawing.Image.FromFile(picPath);

                //水印图片
                System.Drawing.Image waterImage = System.Drawing.Image.FromFile(strWaterFullName);

                //Create   a   new   FrameDimension   object   from   this   image

                FrameDimension ImgFrmDim = new FrameDimension(image.FrameDimensionsList[0]);

                int nFrameCount = image.GetFrameCount(ImgFrmDim);

                //   Save   every   frame   into   jpeg   format

                for (int i = 0; i < nFrameCount; i++)
                {
                    image.SelectActiveFrame(ImgFrmDim, i);

                    image.Save(string.Format(serverPath + "/" + filePath + "Frame{0}.jpg ", i), ImageFormat.Jpeg);
                }
                image.Dispose();

                for (int i = 0; i < nFrameCount; i++)
                {
                    string pa = serverPath + "/" + filePath + "Frame" + i + ".jpg ";
                    System.Drawing.Image Image = System.Drawing.Image.FromFile(pa);
                    Graphics             g     = Graphics.FromImage(Image);
                    g.DrawImage(waterImage, new Rectangle(Image.Width - waterImage.Width, Image.Height - waterImage.Height, waterImage.Width, waterImage.Height), 0, 0, waterImage.Width, waterImage.Height, GraphicsUnit.Pixel);
                    g.Dispose();

                    newPath = serverPath + "/" + filePath + name + i.ToString() + "." + typeName.ToLower();
                    Image.Save(newPath);
                    picRelativePath = filePath + name + i.ToString() + "." + typeName.ToLower();
                    Image.Dispose();

                    if (File.Exists(pa))
                    {
                        File.Delete(pa);
                    }
                }


                if (File.Exists(picPath))
                {
                    File.Delete(picPath);
                }
            }
        }
        return(picRelativePath);
    }
Example #54
0
    private static string UpAddTextWaterImageAndSmallImage(FileUpload upFile, int _picWidth, int _picHeight, int fileSize, string filePath, string serverPath)
    {
        string strFullName      = upFile.PostedFile.FileName;
        string strWaterFullName = serverPath + waterImagePath;
        int    size             = upFile.PostedFile.ContentLength;
        int    j        = strFullName.LastIndexOf("\\") + 1;
        string fileName = strFullName.Substring(j);
        int    a        = fileName.LastIndexOf(".") + 1;
        string typeName = fileName.Substring(a).ToUpper();
        //让系统的时间作为图片的名称
        string name = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
                      System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Millisecond.ToString();
        //保存的文件路径和名称
        string picPath         = serverPath + "/" + filePath + name + ".jpg";
        string newPath         = serverPath + "/" + filePath + name + "new.jpg";
        string picRelativePath = "";
        string smallPicPath    = "";

        if (typeName == "GIF" || typeName == "JPG" || typeName == "PNG" || typeName == "BMP")
        {
            if (fileSize > size)
            {
                //先把文件提交到服务器
                upFile.SaveAs(picPath);
                smallPicPath = serverPath + "/" + filePath + "smallphoto/" + name + "new.jpg";

                //对图片进行缩略
                double picWidth  = Convert.ToDouble(_picWidth);
                double picHeight = Convert.ToDouble(_picHeight);

                System.Drawing.Image im = System.Drawing.Image.FromStream(upFile.PostedFile.InputStream);
                double height           = Convert.ToDouble(im.Height);
                double width            = Convert.ToDouble(im.Width);
                int    suoluetuHeight   = 0;
                int    suoluetuWidth    = 0;
                double beishuHeight     = 1;
                double beishuWidth      = 1;
                if (height > picHeight)
                {
                    beishuHeight = height / picHeight;
                }
                else
                {
                    suoluetuHeight = Convert.ToInt16(height);
                }

                if (width > picWidth)
                {
                    beishuWidth = width / picWidth;
                }
                else
                {
                    suoluetuWidth = Convert.ToInt16(width);
                }

                if (height > width)
                {
                    suoluetuHeight = Convert.ToInt16(height / beishuHeight);
                    suoluetuWidth  = Convert.ToInt16(width / beishuHeight);
                }
                else
                {
                    suoluetuHeight = Convert.ToInt16(height / beishuWidth);
                    suoluetuWidth  = Convert.ToInt16(width / beishuWidth);
                }
                System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                Bitmap myBitmap = new Bitmap(picPath);

                System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(suoluetuWidth, suoluetuHeight, myCallback, IntPtr.Zero);
                //将图像保存到页面输出流中,并制定输出图像的格式

                myThumbnail.Save(smallPicPath, System.Drawing.Imaging.ImageFormat.Jpeg);

                myBitmap.Dispose();



                //加文字水印
                System.Drawing.Image image = System.Drawing.Image.FromFile(picPath);
                Graphics             g     = Graphics.FromImage(image);
                g.DrawImage(image, 20, 20, image.Width, image.Height);
                //在这里设置字体的样式
                Font   f       = new Font("宋体", 60, FontStyle.Italic);
                Brush  b       = new SolidBrush(Color.Black);
                string addText = "Tsolong";
                //在这里设置字体的位置
                g.DrawString(addText, f, b, image.Width - 300, image.Height - 100);
                g.Dispose();
                //保存加水印的图片然后删除原来的图片
                image.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                image.Dispose();
                if (File.Exists(picPath))
                {
                    File.Delete(picPath);
                }

                picRelativePath = filePath + name + "new.jpg";
            }
        }
        return(picRelativePath);
    }
Example #55
0
 /// <summary>
 /// 把选中并设置好的符号在picturebox控件中预览
 /// </summary>
 private void PreviewImage()
 {
     stdole.IPictureDisp  picture = this.axSymbologyControl.GetStyleClass(this.axSymbologyControl.StyleClass).PreviewItem(pStyleGalleryItem, this.ptbPreview.Width, this.ptbPreview.Height);
     System.Drawing.Image image   = System.Drawing.Image.FromHbitmap(new System.IntPtr(picture.Handle));
     this.ptbPreview.Image = image;
 }
Example #56
0
    /// <summary>
    /// 上传大的图片,保存进行缩略加工的图片
    /// </summary>
    /// <param name="upFile"></param>
    /// <param name="_picWidth"></param>
    /// <param name="_picHeight"></param>
    /// <param name="fileSize"></param>
    /// <param name="filePath"></param>
    /// <param name="serverPath"></param>
    /// <returns></returns>
    private static string UploadAddSmallImageAndImage(FileUpload upFile, int _picWidth, int _picHeight, int fileSize, string filePath, string serverPath)
    {
        int    size     = upFile.PostedFile.ContentLength;
        string fileName = upFile.PostedFile.FileName;
        int    a        = fileName.LastIndexOf(".") + 1;
        string typeName = fileName.Substring(a).ToUpper();
        string name     = DateTime.Now.ToString("yyyyMMddhhmmss") + "." + typeName.ToLower();
        string path     = serverPath + "/" + filePath + name;
        string picPath  = "";

        if (typeName == "GIF" || typeName == "JPG" || typeName == "PNG" || typeName == "BMP")
        {
            if (size > fileSize)
            {
                return(picPath);
            }
            else
            {
                upFile.PostedFile.SaveAs(path);
                double picWidth  = Convert.ToDouble(_picWidth);
                double picHeight = Convert.ToDouble(_picHeight);

                System.Drawing.Image im = System.Drawing.Image.FromStream(upFile.PostedFile.InputStream);
                double height           = Convert.ToDouble(im.Height);
                double width            = Convert.ToDouble(im.Width);
                int    suoluetuHeight   = 0;
                int    suoluetuWidth    = 0;
                double beishuHeight     = 1;
                double beishuWidth      = 1;
                if (height > picHeight)
                {
                    beishuHeight = height / picHeight;
                }
                else
                {
                    suoluetuHeight = Convert.ToInt16(height);
                }

                if (width > picWidth)
                {
                    beishuWidth = width / picWidth;
                }
                else
                {
                    suoluetuWidth = Convert.ToInt16(width);
                }

                if (height > width)
                {
                    suoluetuHeight = Convert.ToInt16(height / beishuHeight);
                    suoluetuWidth  = Convert.ToInt16(width / beishuHeight);
                }
                else
                {
                    suoluetuHeight = Convert.ToInt16(height / beishuWidth);
                    suoluetuWidth  = Convert.ToInt16(width / beishuWidth);
                }
                System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                Bitmap myBitmap = new Bitmap(path);
                //图片制作缩略图
                System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(suoluetuWidth, suoluetuHeight, myCallback, IntPtr.Zero);
                //将图像保存到页面输出流中,并制定输出图像的格式
                string smallPath = serverPath + "/" + filePath + "smallphoto/" + name;
                picPath = filePath + name;
                myThumbnail.Save(smallPath, System.Drawing.Imaging.ImageFormat.Jpeg);

                myBitmap.Dispose();

                return(picPath);
            }
        }
        else
        {
            return(picPath);
        }
    }
Example #57
0
 private void SaveImage(Stream outputContent, DrImage target)
 => target.Save(outputContent, formatDefinition.Codec, formatDefinition.EncoderParameters);
Example #58
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径</param>
        /// <param name="thumbnailPath">缩略图路径</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式:HW指定高宽缩放(可能变形);W指定宽,高按比例 H指定高,宽按比例 Cut指定高宽裁减(不变形)</param>  
        /// <param name="mode">要缩略图保存的格式(gif,jpg,bmp,png) 为空或未知类型都视为jpg</param>  
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, string imageType)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth  = width;
            int toheight = height;
            int x        = 0;
            int y        = 0;
            int ow       = originalImage.Width;
            int oh       = originalImage.Height;

            switch (mode)
            {
            case "HW":    //指定高宽缩放(可能变形)        
                break;

            case "W":    //指定宽,高按比例          
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":    //指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":    //指定高宽裁减(不变形)        
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                        new Rectangle(x, y, ow, oh),
                        GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                switch (imageType.ToLower())
                {
                case "gif":
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
                    break;

                case "jpg":
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;

                case "bmp":
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case "png":
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
                    break;

                default:
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Example #59
0
        public TileItem AddImage(TileImageInfo imgInfo)
        {
            TileItem AddImageToTile(System.Drawing.Image img)
            {
                TileItem ti = new TileItem();

                ti.Image          = img;
                ti.ImageScaleMode = TileItemImageScaleMode.Stretch;
                ti.ItemSize       = TileItemSize.Large;
                ti.Text           = "";
                ti.Tag            = imgInfo;

                TileItemElement tie = new TileItemElement();

                tie.Image          = imageList1.Images[0];
                tie.ImageSize      = new Size(32, 32);
                tie.ImageAlignment = TileItemContentAlignment.TopRight;
                tie.Text           = "";

                ti.Elements.Add(tie);

                if (imgInfo.IsKeyImage)
                {
                    TileItemElement tieKey = new TileItemElement();

                    tieKey.Image          = imageList2.Images[1];
                    tieKey.Image.Tag      = "lock";
                    tieKey.ImageSize      = new Size(16, 16);
                    tieKey.ImageAlignment = TileItemContentAlignment.TopLeft;
                    tieKey.Text           = "";

                    ti.Elements.Add(tieKey);
                }

                TileItemElement tieOrder = new TileItemElement();

                tieOrder.TextAlignment = TileItemContentAlignment.BottomLeft;
                tieOrder.Text          = imgInfo.Order;


                ti.Elements.Add(tieOrder);

                if (tileControl1.Groups.Count <= 0)
                {
                    TileGroup tg = new TileGroup();
                    tg.Text = "";

                    tileControl1.Groups.Add(tg);
                }


                if (tileControl1.Groups[0].Items.Count >= _imgViewCount)
                {
                    tileControl1.Groups[0].Items.RemoveAt(0);
                }

                tileControl1.Groups[0].Items.Insert(0, ti);
                //tileControl1.Groups[0].Items.Add(ti);

                return(ti);
            }

            if (this.InvokeRequired)//如果是在非创建控件的线程访问,即InvokeRequired=true
            {
                DelegateAddImage addImgProcess = new DelegateAddImage(AddImage);
                return(this.Invoke(addImgProcess, new object[] { imgInfo }) as TileItem);
            }
            else
            {
                System.Drawing.Image img = null;
                //视频音频类型媒体加载判断处理
                if (imgInfo.MediaType == "视频")
                {
                    img = imageList3.Images[0];
                }
                else if (imgInfo.MediaType == "音频")
                {
                    img = imageList3.Images[1];
                }
                else
                {
                    img = ImageEx.LoadFile(imgInfo.File);
                }

                return(AddImageToTile(img));
            }
        }
Example #60
0
    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
        if (e.CommandName == "alpha" || e.CommandName == "NoFilter")
        {
            String value = null;
            switch (e.CommandName)
            {
            case ("alpha"):
            {
                value = string.Format("{0}%", e.CommandArgument);
                break;
            }

            case ("NoFilter"):
            {
                value = "%";
                break;
            }
            }
            ObjectDataSource1.SelectParameters["CompanyName"].DefaultValue = value;
            ObjectDataSource1.DataBind();
            RadGrid1.Rebind();
        }
        else if (e.CommandName == "QuickUpdate")
        {
            string AdsBannerID, Priority, IsAvailable;
            var    oAdsBanner = new AdsBanner();

            foreach (GridDataItem item in RadGrid1.Items)
            {
                AdsBannerID = item.GetDataKeyValue("AdsBannerID").ToString();
                Priority    = ((RadNumericTextBox)item.FindControl("txtPriority")).Text.Trim();
                IsAvailable = ((CheckBox)item.FindControl("chkIsAvailable")).Checked.ToString();

                oAdsBanner.AdsBannerQuickUpdate(
                    AdsBannerID,
                    Priority,
                    IsAvailable
                    );
            }
        }
        else if (e.CommandName == "DeleteSelected")
        {
            var oAdsBanner = new AdsBanner();

            foreach (GridDataItem item in RadGrid1.SelectedItems)
            {
                string strFileName = ((HiddenField)item.FindControl("hdnFileName")).Value;

                if (!string.IsNullOrEmpty(strFileName))
                {
                    string strSavePath = Server.MapPath("~/res/advertisement/" + strFileName);
                    if (File.Exists(strSavePath))
                    {
                        File.Delete(strSavePath);
                    }
                }
            }
        }
        else if (e.CommandName == "PerformInsert" || e.CommandName == "Update")
        {
            var command      = e.CommandName;
            var row          = command == "PerformInsert" ? (GridEditFormInsertItem)e.Item : (GridEditFormItem)e.Item;
            var FileFileName = (RadUpload)row.FindControl("FileFileName");
            var dpFromDate   = (RadDatePicker)row.FindControl("dpFromDate");
            var dpToDate     = (RadDatePicker)row.FindControl("dpToDate");

            string strCompanyName = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtCompanyName")).Content.Trim()));//((TextBox)row.FindControl("txtCompanyName")).Text.Trim();
            //string strTitle = ((TextBox)row.FindControl("txtTitle")).Text.Trim();
            //string strDescription = ((TextBox)row.FindControl("txtDescription")).Text.Trim();
            string strConvertedAdsBannerName = Common.ConvertTitle(strCompanyName);
            string strFileName      = FileFileName.UploadedFiles.Count > 0 ? FileFileName.UploadedFiles[0].GetName() : "";
            string strIsAvailable   = ((CheckBox)row.FindControl("chkIsAvailable")).Checked.ToString();
            string strPriority      = ((RadNumericTextBox)row.FindControl("txtPriority")).Text.Trim();
            string strFromDate      = dpFromDate.SelectedDate.HasValue ? dpFromDate.SelectedDate.Value.ToString("MM/dd/yyyy") : "";
            string strToDate        = dpToDate.SelectedDate.HasValue ? dpToDate.SelectedDate.Value.ToString("MM/dd/yyyy") : "";
            string strAdsCategoryID = "7";// ((RadComboBox)row.FindControl("ddlCategory")).SelectedValue;
            string strWebsite       = ((TextBox)row.FindControl("txtWebsite")).Text.Trim();
            double ratio            = 0;

            if (!string.IsNullOrEmpty(strFileName))
            {
                string strTempPath = Server.MapPath(FileFileName.TargetFolder + strFileName);
                if (IsImageFormat(strFileName))
                {
                    System.Drawing.Image img = System.Drawing.Image.FromFile(strTempPath);
                    ratio = (double)img.Width / (img.Height == 0 ? 1 : img.Height);
                    img.Dispose();
                }
                else
                {
                    SwfParser swfParser = new SwfParser();
                    Rectangle rectangle = swfParser.GetDimensions(strTempPath);
                    ratio = (double)rectangle.Width / (rectangle.Height == 0 ? 1 : rectangle.Height);
                }
                string[] files = Directory.GetFiles(Server.MapPath(FileFileName.TargetFolder));

                foreach (string filePath in files)
                {
                    File.Delete(filePath);
                }
            }

            var oAdsBanner = new AdsBanner();

            if (e.CommandName == "PerformInsert")
            {
                strFileName = oAdsBanner.AdsBannerInsert(
                    strFileName,
                    strConvertedAdsBannerName,
                    strAdsCategoryID,
                    strCompanyName,
                    strWebsite,
                    strFromDate,
                    strToDate,
                    strPriority,
                    strIsAvailable,
                    ratio == 0 ? "" : ratio.ToString().Replace(',', '.')
                    );

                string strFullPath = "~/res/advertisement/" + strFileName;

                if (!string.IsNullOrEmpty(strFileName))
                {
                    FileFileName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath));
                    if (IsImageFormat(strFileName))
                    {
                        //ResizeCropImage.ResizeByCondition(strFullPath, 800, 800);
                    }
                }
                RadGrid1.Rebind();
            }
            else
            {
                var dsUpdateParam   = ObjectDataSource1.UpdateParameters;
                var strAdsBannerID  = row.GetDataKeyValue("AdsBannerID").ToString();
                var strOldFileName  = ((HiddenField)row.FindControl("hdnFileName")).Value;
                var strOldImagePath = Server.MapPath("~/res/advertisement/" + strOldFileName);

                dsUpdateParam["FileName"].DefaultValue = strFileName;
                dsUpdateParam["ConvertedAdsBannerName"].DefaultValue = strConvertedAdsBannerName;
                dsUpdateParam["AdsCategoryID"].DefaultValue          = strAdsCategoryID;
                dsUpdateParam["FromDate"].DefaultValue    = strFromDate;
                dsUpdateParam["ToDate"].DefaultValue      = strToDate;
                dsUpdateParam["IsAvailable"].DefaultValue = strIsAvailable;
                dsUpdateParam["Ratio"].DefaultValue       = ratio == 0 ? "" : ratio.ToString().Replace(',', '.');

                if (!string.IsNullOrEmpty(strFileName))
                {
                    var strFullPath = "~/res/advertisement/" + (string.IsNullOrEmpty(strConvertedAdsBannerName) ? "" : strConvertedAdsBannerName + "-") + strAdsBannerID + strFileName.Substring(strFileName.LastIndexOf('.'));

                    if (File.Exists(strOldImagePath))
                    {
                        File.Delete(strOldImagePath);
                    }

                    FileFileName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath));
                    if (IsImageFormat(strFileName))
                    {
                        //ResizeCropImage.ResizeByCondition(strFullPath, 654, 654);
                    }
                }
            }
        }
        if (e.CommandName == "DeleteImage")
        {
            var oAdsBanner     = new AdsBanner();
            var lnkDeleteImage = (LinkButton)e.CommandSource;
            var s = lnkDeleteImage.Attributes["rel"].ToString().Split('#');
            var strAdsBannerID = s[0];
            var strFileName    = s[1];

            oAdsBanner.AdsBannerDelete(strAdsBannerID);
            DeleteImage(strFileName);
            RadGrid1.Rebind();
        }
    }