Пример #1
2
 /// <summary>
 /// Convert Image to Byte[]
 /// Image img = Image.FromFile("c:\\hcha.jpg");
 /// </summary>
 /// <param name="image"></param>
 /// <returns></returns>
 public static byte[] ImageToBytes(Image image)
 {
     ImageFormat format = image.RawFormat;
     using (MemoryStream ms = new MemoryStream())
     {
         if (format.Equals(ImageFormat.Jpeg))
         {
             image.Save(ms, ImageFormat.Jpeg);
         }
         else if (format.Equals(ImageFormat.Png))
         {
             image.Save(ms, ImageFormat.Png);
         }
         else if (format.Equals(ImageFormat.Bmp))
         {
             image.Save(ms, ImageFormat.Bmp);
         }
         else if (format.Equals(ImageFormat.Gif))
         {
             image.Save(ms, ImageFormat.Gif);
         }
         else if (format.Equals(ImageFormat.Icon))
         {
             image.Save(ms, ImageFormat.Icon);
         }
         byte[] buffer = new byte[ms.Length];
         //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin
         ms.Seek(0, SeekOrigin.Begin);
         ms.Read(buffer, 0, buffer.Length);
         return buffer;
     }
 }
Пример #2
1
 public static string FromImageV4(Image val)
 {
     MemoryStream stream = new MemoryStream();
     try
     {
         val.Save(stream, val.RawFormat);
     }
     catch (ArgumentNullException)
     {
         val.Save(stream, ImageFormat.Bmp);
     }
     return FromStreamV4(stream);
 }
Пример #3
1
 public static string FromImage(Image val)
 {
     MemoryStream stream = new MemoryStream();
     try
     {
         val.Save(stream, val.RawFormat);
     }
     catch (ArgumentNullException)
     {
         val.Save(stream, ImageFormat.Bmp);
     }
     return Convert.ToBase64String(stream.GetBuffer());
 }
Пример #4
1
    protected string SaveImg()
    {
        string filetype = FileUpload1.PostedFile.ContentType;//איתור סוג הקובץ

        //בדיקה האם הקובץ הנקלט הוא מסוג תמונה
        if (filetype.Contains("image"))
        {
            //איתור שם הקובץ
            string fileName = FileUpload1.PostedFile.FileName;
            //איתור סיומת הקובץ
            string endOfFileName = fileName.Substring(fileName.LastIndexOf("."));
            //איתור זמן העלת הקובץ
            string myTime = DateTime.Now.ToString("dd_MM_yy_HH_mm_ss");
            //הגדרת שם חדש לקובץ
            string imageNewName = myTime + endOfFileName;


            // Bitmap המרת הקובץ שיתקבל למשתנה מסוג
            System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(FileUpload1.PostedFile.InputStream);

            //קריאה לפונקציה המקטינה את התמונה
            //אנו שולחים לה את התמונה שלנו בגירסאת הביטמאפ ואת האורך והרוחב שאנו רוצים לתמונה החדשה
            System.Drawing.Image objImage = FixedSize(bmpPostedImage, 300, 300);



            //שמירת הקובץ בגודלו החדש בתיקייה
            objImage.Save(Server.MapPath(imagesLibPath) + imageNewName);
            return(imageNewName);
        }
        else
        {
            Response.Write("<script LANGUAGE='JavaScript' >alert('הקובץ אינו תמונה ולכן לא ניתן להעלות אותו')</script>");
            return(null);
        }
    }
Пример #5
0
        public static byte[] PackScreenCaptureData(Guid id, Image image, Rectangle bounds)
        {
            var idData = id.ToByteArray();

            byte[] imgData;
            using (var ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                imgData = ms.ToArray();
            }

            var topData = BitConverter.GetBytes(bounds.Top);
            var botData = BitConverter.GetBytes(bounds.Bottom);
            var leftData = BitConverter.GetBytes(bounds.Left);
            var rightData = BitConverter.GetBytes(bounds.Right);

            var sizeOfInt = topData.Length;
            var result = new byte[imgData.Length + (4 * sizeOfInt) + idData.Length];
            Array.Copy(topData, 0, result, 0, topData.Length);
            Array.Copy(botData, 0, result, sizeOfInt, botData.Length);
            Array.Copy(leftData, 0, result, 2 * sizeOfInt, leftData.Length);
            Array.Copy(rightData, 0, result, 3 * sizeOfInt, rightData.Length);
            Array.Copy(imgData, 0, result, 4 * sizeOfInt, imgData.Length);
            Array.Copy(idData, 0, result, (4 * sizeOfInt) + imgData.Length, idData.Length);

            return result;
        }
Пример #6
0
 public void AddImage(string name, Image image)
 {
     using (image)
     {
         string path = Path.Combine(Constants.CacheLocation, name + SaveableFileTypes.Png);
         Console.WriteLine(Constants.CacheLocation, name + SaveableFileTypes.Png);
         try
         {
             if(File.Exists(path))
             {
                 //something may still have a handle on the previous "temp" image
                 //this forces it to be GC'd
                 GC.Collect();
                 GC.WaitForPendingFinalizers();
                 File.Delete(path);
             }
             image.Save(path, ImageFormat.Png);
         }
         catch (System.Runtime.InteropServices.ExternalException e)
         {
             MessageBox.Show($"Unable to add image temporary image cache. Reason: {e}");
         }
         catch(IOException ioe)
         {
             MessageBox.Show(ioe.ToString());
         }
     }
 }
Пример #7
0
        private static dynamic PostImage(string url, Image image)
        {
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] bytes = ms.ToArray();

            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "image/jpeg";
            request.ContentLength = bytes.Length;
            Stream s = request.GetRequestStream();
            s.Write(bytes, 0, bytes.Length);
            s.Close();

            WebResponse response = request.GetResponse();
            byte[] rdata;
            using (var stream = new MemoryStream())
            {
                response.GetResponseStream().CopyTo(stream);
                rdata = stream.ToArray();
            }

            string resp = System.Text.Encoding.UTF8.GetString(rdata);
            return JsonConvert.DeserializeObject(resp);
        }
		public void SaveImage(Image image, string fileName)
		{
			if (image == null) return;
			image.Save(Path.Combine(ResourceManager.Instance.FavoriteImagesFolder.LocalPath, String.Format("{0}.png", fileName)));
			LoadImages();
			OnCollectionChanged();
		}
Пример #9
0
 public static void SaveJpegToStreamWithCompressionSetting(Image image, long compression, Stream savestream)
 {
     var eps = new EncoderParameters(1);
     eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compression);
     var ici = GetEncoderInfo("image/jpeg");
     image.Save(savestream, ici, eps);
 }
Пример #10
0
        // Convertit une image en bytes
        public static byte[] getBytesFromImage(Image im)
        {
            MemoryStream ms = new MemoryStream();

            im.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }
Пример #11
0
        public string SaveImage(string IMAGE_PATH, string base64string, int locationId)
        {
            bytes = Convert.FromBase64String(base64string);

            using (ms = new MemoryStream(bytes))
            {
                image = Image.FromStream(ms);

                // Check image dimensions
                if (
                    image.Width > MAX_IMAGE_WIDTH ||
                    image.Height > MAX_IMAGE_HEIGHT ||
                    image.Width < MIN_IMAGE_WIDTH ||
                    image.Height < MIN_IMAGE_HEIGHT
                   )
                {
                    throw new Exception("Maximum image dimensions are: Width: 400px and Height: 400px. Minimum image dimensions are: Width: 10px and Height 10px.");
                }

                // Build uploadpath
                UploadImagePath = HttpContext.Current.Server.MapPath(String.Format(@"~/{0}", IMAGE_PATH));

                // Save image
                image.Save(String.Format("{0}/{1}.jpg", UploadImagePath, locationId), System.Drawing.Imaging.ImageFormat.Jpeg);

                // Return relative path to image
                return String.Format("{0}/{1}.jpg", IMAGE_PATH, locationId);
            }
        }
Пример #12
0
 public void SetPoster(Image img)
 {
     if (img == null) return;
     MemoryStream ms = new MemoryStream();
     img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
     Poster = ms.ToArray();
 }
Пример #13
0
 public ImagePath( Image Image, ImageOwner ImageOwner, String Description )
     : base()
 {
     this.Description = Description;
     this.ImageOwner = ImageOwner;
     Image.Save( "~/Content/Images/" + this.ImageOwner.RID.ToString() + "/" +  this.RID.ToString());
 }
        public static byte[] CompressImage(Image ImageToCompress, long CompressionLevel)
        {
            //grab the memory stream to save into
            using (var MemoryStreamToSave = new MemoryStream())
            {
                //declare the parameters
                var EncoderParams = new EncoderParameters(1);

                //set the compression level
                EncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, CompressionLevel);

                //grab the codec info
                var EncoderInfo = GetEncoderInfo("image/jpeg");

                //go save the image to the memory stream
                ImageToCompress.Save(MemoryStreamToSave, EncoderInfo, EncoderParams);

                //close the memory stream
                MemoryStreamToSave.Flush();

                //close the memory stream
                MemoryStreamToSave.Close();

                //return the byte array now
                return MemoryStreamToSave.ToArray();
            }
        }
Пример #15
0
 public bool InsertPicture(string code, Image img)
 {
     MemoryStream ms = new MemoryStream();
     img.Save(ms, img.RawFormat);
     byte[] image_byte = ms.GetBuffer();
     return _DA.insert_picture_2DB(code, image_byte);
 }
Пример #16
0
        public static void CompressImage(Image sourceImage, int imageQuality, string savePath)
        {
            try
            {
                //Create an ImageCodecInfo-object for the codec information
                ImageCodecInfo jpegCodec = null;

                //Set quality factor for compression
                EncoderParameter imageQualitysParameter = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, imageQuality);

                //List all avaible codecs (system wide)
                ImageCodecInfo[] alleCodecs = ImageCodecInfo.GetImageEncoders();

                EncoderParameters codecParameter = new EncoderParameters(1);
                codecParameter.Param[0] = imageQualitysParameter;

                //Find and choose JPEG codec
                for (int i = 0; i < alleCodecs.Length; i++)
                {
                    if (alleCodecs[i].MimeType == "image/jpeg")
                    {
                        jpegCodec = alleCodecs[i];
                        break;
                    }
                }

                //Save compressed image
                sourceImage.Save(HttpContext.Current.Server.MapPath(savePath), jpegCodec, codecParameter);
            }
            catch (Exception ex)
            {

            }
        }
Пример #17
0
        public byte[] SerializeDesktopCapture(Image capture, Rectangle rectBounds)
        {
            byte[] data = _id.ToByteArray();
            byte[] Buffer;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                capture.Save(memoryStream, ImageFormat.Jpeg);
                Buffer = memoryStream.ToArray();
            }
            // get the bounds
            byte[] rectTopBound = BitConverter.GetBytes(rectBounds.Top);
            byte[] rectBottomBound = BitConverter.GetBytes(rectBounds.Bottom);
            byte[] rectLeftBound = BitConverter.GetBytes(rectBounds.Left);
            byte[] rectRightBound = BitConverter.GetBytes(rectBounds.Right);

            // create final bytes
            int size = rectTopBound.Length;
            byte[] serializedScreen = new byte[Buffer.Length + 4 * size + data.Length];
            Array.Copy(rectTopBound, 0, serializedScreen, 0, rectTopBound.Length);
            Array.Copy(rectBottomBound, 0, serializedScreen, size, rectBottomBound.Length);
            Array.Copy(rectLeftBound, 0, serializedScreen, 2 * size, rectLeftBound.Length);
            Array.Copy(rectRightBound, 0, serializedScreen, 3 * size, rectRightBound.Length);
            Array.Copy(Buffer, 0, serializedScreen, 4 * size, Buffer.Length);
            Array.Copy(data, 0, serializedScreen, 4 * size + Buffer.Length, data.Length);
            return serializedScreen;
        }
Пример #18
0
        public static string CaptureAndPost(Image img)
        {
            //string uploadurl = "http://yfrog.com/api/upload";
            string twitusername = "******";
            string twitpassword = "";
            string yfrogkey = "";

            MemoryStream ms = new MemoryStream();
            img.Save(ms,ImageFormat.Jpeg);
            byte[] data = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(data,0,(int)ms.Length);

            string url = "";
            int attempts = 4;
            for (int a = 1; a < attempts; a++) {
                url = DoPost(data,twitusername,twitpassword,yfrogkey);
                if (url != "") {
                    break;
                }
                log.WarnFormat("Failed to upload image, attempt {0}",a);
                System.Threading.Thread.Sleep(2000);
            }
            if (url == "")
            {
                log.FatalFormat("Unable to upload after {0} attempts",attempts);
            }

            return url;
        }
Пример #19
0
        public string UploadImage(Image image)
        {
            // TODO: maybe a global lock while we upload this image?

            var fileName = RandomKey() + ".jpg";
            while (_thumbnailDirectory.FileExists(fileName))
                fileName = RandomKey() + ".jpg";

            try
            {
                _thumbnailDirectory.GetFile(fileName).Open(FileMode.Create, stream => image.Save(stream, ImageFormat.Jpeg));
            }
            catch (Exception)
            {
                try
                {
                    // if there was any issue, try to delete the file, if we created
                    if (_thumbnailDirectory.FileExists(fileName))
                        _thumbnailDirectory.DeleteFile(fileName);
                }
                catch (Exception)
                {
                    // the error was more fundamental.
                    // don't do anything with this exception.
                    // let the previous exception be the real one thrown.
                }
                throw;
            }

            return fileName;
        }
Пример #20
0
 /// <summary>
 /// Save an Image as a JPeg with a given compression
 ///  Note: Filename suffix will not affect mime type which will be Jpeg.
 /// </summary>
 /// <param name="image">Image: Image to save</param>
 /// <param name="fileName">String: File name to save the image as. Note: suffix will not affect mime type which will be Jpeg.</param>
 /// <param name="compression">Long: Value between 0 and 100.</param>
 private static void SaveJpegWithCompressionSetting(Image image, string fileName, long compression)
 {
     var eps = new EncoderParameters(1);
     eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compression);
     var ici = GetEncoderInfo("image/jpeg");
     image.Save(fileName, ici, eps);
 }
Пример #21
0
 public static Stream ImageToStream(Image image, ImageFormat formaw)
 {
     var stream = new MemoryStream();
     image.Save(stream, formaw);
     stream.Position = 0;
     return stream;
 }
Пример #22
0
        public static byte[] ResizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent;
            float nPercentW;
            float nPercentH;

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

            nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

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

            var bitmap = new Bitmap(destWidth, destHeight);
            var graphics = Graphics.FromImage(bitmap);
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            graphics.Dispose();
            using (var ms = new MemoryStream())
            {
                imgToResize.Save(ms, ImageFormat.Jpeg);
                return ms.GetBuffer();
            }
        }
Пример #23
0
            /// <summary>
            /// Convert Tiff image to another mime-type bitmap
            /// </summary>
            /// <param name="tiffImage">Source TIFF file</param>
            /// <param name="mimeType">Desired result mime-type</param>
            /// <returns>Converted image</returns>
            public Bitmap ConvertTiffToBitmap(Image tiffImage, string mimeType)
            {
                var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == "image/tiff");

                if (imageCodecInfo == null)
                {
                    return null;
                }
                Bitmap sourceImg;

                using (var memoryStream = new MemoryStream())
                {
                    // Setting encode params
                    var imageEncoderParams = new EncoderParameters(1);
                    imageEncoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                    tiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams);
                    tiffImage.Dispose();

                    var ic = new ImageConverter();

                    // Reading stream data to new image
                    var tempTiffImage = (Image)ic.ConvertFrom(memoryStream.GetBuffer());

                    // Setting new result mime-type
                    imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == mimeType);
                    if (tempTiffImage != null) tempTiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams);

                    sourceImg = new Bitmap(Image.FromStream(memoryStream, true));

                }

                return sourceImg;
            }
Пример #24
0
        // Convert image to post it to FB.
        public byte[] ImageToByteArray(Image i_ImageIn)
        {
            MemoryStream imageStream = new MemoryStream();
            i_ImageIn.Save(imageStream, System.Drawing.Imaging.ImageFormat.Gif);

            return imageStream.ToArray();
        }
Пример #25
0
        public string GetCaptcha(Image image)
        {
            bool flag = true;
            int retries = 5;
            string id = "";

            MemoryStream ms = new MemoryStream();
            image.Save(ms,ImageFormat.Jpeg);
            string data = Convert.ToBase64String(ms.ToArray());
            data = WebUtility.UrlEncode(data);
            data = String.Format(inData, token, data);

            while (flag && retries > 0)
            {
                flag = false;
                WebClient web = new WebClient();
                web.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                try
                {
                    string res = web.UploadString(inUrl, data);
                    if (res.Contains("OK|"))
                        id = res.Substring(3);
                    else throw new CaptchaErrorException();
                }
                catch (Exception)
                {
                    retries--;
                    flag = true;
                }
            }
            if (flag)
                return null;

            return GetResponse(id);
        }
        public void Process(Image wallpaper)
        {
            try
            {
                DirectoryInfo appData = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
                DirectoryInfo applicationDirectory = appData.CreateSubdirectory("Adhesive");

                string wallpaperPath = applicationDirectory.FullName + "\\wallpaper.jpg";
                wallpaper.Save(wallpaperPath, System.Drawing.Imaging.ImageFormat.Bmp);

                RegistryKey desktop = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
                desktop.SetValue("TileWallpaper", "1");
                desktop.SetValue("WallpaperStyle", "0");

                if (SystemParametersInfo(SPI_SETDESKWALLPAPER, 0,
                    wallpaperPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE) == 0)
                {
                    throw new Exception("SystemParametersInfo failed");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to set wallpaper: " + ex.Message);
            }
        }
Пример #27
0
 public static void SaveTemporaryImage(string filename, Image image) {
     string tempDir = ConfigUtil.GetUserAppDir("temp.net");
     string file = Path.Combine(tempDir, filename);
     lock (syncLock) {
         image.Save(file, ImageFormat.Jpeg);
     }
 }
Пример #28
0
        public bool AddOrUpdateMapTile(SceneInfo sceneInfo, Image mapTile)
        {
            if (m_assetClient == null)
                return false;

            int zoomLevel = 1;
            uint x = (uint)sceneInfo.MinPosition.X / 256u;
            uint y = (uint)sceneInfo.MinPosition.Y / 256u;

            byte[] pngData;
            using (MemoryStream stream = new MemoryStream())
            {
                mapTile.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                pngData = stream.ToArray();
            }

            Asset asset = new Asset
            {
                ContentType = "image/png",
                CreationDate = DateTime.UtcNow,
                CreatorID = sceneInfo.ID,
                Data = pngData,
                ID = TileNameToUUID(zoomLevel, x, y)
            };

            // TODO: Create and store the other zoom levels
            return m_assetClient.StoreAsset(asset);
        }
Пример #29
0
 public byte[] ImageToByteArray(Image imageIn, string imageFormatString)
 {
     var ms = new MemoryStream();
     var imageFormat = getImageFormat(imageFormatString);
     imageIn.Save(ms, imageFormat);
     return ms.ToArray();
 }
Пример #30
0
        public static byte[] SerializeCapture(Image capture, Rectangle rect)
        {
            byte[] data = _id.ToByteArray();
            byte[] temp;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                capture.Save(memoryStream, ImageFormat.Jpeg);
                temp = memoryStream.ToArray();
            }
            // get the bounds
            byte[] rectTop = BitConverter.GetBytes(rect.Top);
            byte[] rectBottom = BitConverter.GetBytes(rect.Bottom);
            byte[] rectLeft = BitConverter.GetBytes(rect.Left);
            byte[] rectRight = BitConverter.GetBytes(rect.Right);

            // create final bytes
            int size = rectTop.Length;
            byte[] serialized = new byte[temp.Length + 4 * size + data.Length];
            Array.Copy(rectTop, 0, serialized, 0, rectTop.Length);
            Array.Copy(rectBottom, 0, serialized, size, rectBottom.Length);
            Array.Copy(rectLeft, 0, serialized, 2 * size, rectLeft.Length);
            Array.Copy(rectRight, 0, serialized, 3 * size, rectRight.Length);
            Array.Copy(temp, 0, serialized, 4 * size, temp.Length);
            Array.Copy(data, 0, serialized, 4 * size + temp.Length, data.Length);
            return serialized;
        }
Пример #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());
            }
        }
Пример #32
0
 public void RenderToStream()
 {
     if (m_currentByteCount > 0 && ImageInfos.Count > 0)
     {
         string streamName = GetStreamName();
         Stream stream     = m_createAndRegisterStream(streamName, "png", null, PageContext.PNG_MIME_TYPE, willSeek: false, StreamOper.CreateAndRegister);
         using (System.Drawing.Image image = Render())
         {
             image?.Save(stream, ImageFormat.Png);
         }
     }
     CurrentOffset++;
     m_currentByteCount = 0;
     MaxHeight          = 0;
     MaxWidth           = 0;
 }
Пример #33
0
    private void saveURLToImage(string url)
    {
        if (!string.IsNullOrEmpty(url))
        {
            string content = "";

            System.Net.WebRequest  webRequest__1 = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webResponse   = webRequest__1.GetResponse();
            System.IO.StreamReader sr            = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
            content = sr.ReadToEnd();
            //save to file
            byte[] b = Convert.FromBase64String(content);
            System.IO.MemoryStream ms  = new System.IO.MemoryStream(b, 0, b.Length);
            System.Drawing.Image   img = System.Drawing.Image.FromStream(ms);
            img.Save("c:\\pic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            img.Dispose();
            ms.Close();
        }
    }
Пример #34
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         GameManager GM   = new GameManager();
         GameTBx     game = new GameTBx();
         game             = GM.GetByID(Convert.ToInt32(Request["id"]));
         game.status      = 1;
         game.name        = Request["name"];
         game.link        = Request["link"];
         game.description = Request.Unvalidated["desc"];
         game.content     = Request.Unvalidated["cont"];
         string base64 = Request["base64"];
         try
         {
             byte[]       imageBytes = Convert.FromBase64String(base64);
             MemoryStream ms         = new MemoryStream(imageBytes, 0, imageBytes.Length);
             ms.Write(imageBytes, 0, imageBytes.Length);
             System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
             string fileName            = "game_" + game.id + ".jpg";
             image.Save(Path.Combine(Server.MapPath("~/upload/game"), fileName));
             game.banner = "/upload/game/" + fileName;
         }
         catch
         {
         }
         GM.Save();
         Response.Write(JsonConvert.SerializeObject(new
         {
             success = 1
         }));
     }
     catch (Exception ex)
     {
         Response.Write(JsonConvert.SerializeObject(new
         {
             success = -1,
             error   = ex
         }));
     }
 }
Пример #35
0
    protected void lnkSign2_Click(object sender, EventArgs e)
    {
        try
        {
            //To Delete All Files In Direcotry===========
            string[] filePaths = System.IO.Directory.GetFiles(Server.MapPath("~/Images/Temp/"));
            foreach (string filePath in filePaths)
            {
                System.IO.File.Delete(filePath);
            }
            //To Delete All Files In Direcotry===========
            Random random = new Random();

            if (DigitalSignUpload3.HasFile)
            {
                //--Total No of Files--
                Int64 TotalFiles = System.IO.Directory.GetFiles(Server.MapPath("~/Images/Imgupload")).Count();

                string filename = System.IO.Path.GetFileName(DigitalSignUpload3.FileName);
                filename = TotalFiles + "-" + filename;
                DigitalSignUpload3.SaveAs(Server.MapPath("~/Images/Temp/") + filename);

                //==========USed For Resize Image to Gal Size===================
                System.Drawing.Image GalImage = obj_Comm.ResizeImage(System.Drawing.Image.FromFile(Server.MapPath("~/Images/Temp/") + filename), 200, 200);
                GalImage.Save(Server.MapPath("~/Images/Imgupload/") + filename);
                GalImage = null;
                //==========USed For Resize Image to Gal Size===================


                //==========USed For Resize Image to Thumb===================
                LblSignPath2.Text = "~/Images/Imgupload/" + filename;
                //ImgDone.Visible = true;
                ImgSign2.ImageUrl = @"~/Images/Imgupload/" + filename;
                ImgSign2.DataBind();
            }
        }
        catch (Exception ex)
        {
            obj_Comm.ShowPopUpMsg("Upload status: The file could not be uploaded. The following error occured: " + ex.Message, this.Page);
        }
    }
Пример #36
0
    public void ProcessRequest(System.Web.HttpContext context)
    {
        HttpRequest  Request  = context.Request;
        HttpResponse response = context.Response;

        Barcode39 bc39 = new Barcode39();

        if (Request["code"] != null)
        {
            bc39.Code = Request["code"];
        }
        else
        {
            bc39.Code = DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString();
        }

        System.Drawing.Image bc = bc39.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White);
        response.ContentType = "image/gif";

        bc.Save(response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
    }
Пример #37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string num = Request["num"].ToString();
        int    w   = Request["w"] == null ? 1 : int.Parse(Request["w"].ToString());
        int    h   = Request["h"] == null ? 30 : int.Parse(Request["h"].ToString());
        string s   = Request["s"] == null ? "1" : Request["s"].ToString();
        //string num = "KM20110715002";
        bool lb_s = true;

        if (s == "0")
        {
            lb_s = false;
        }
        System.IO.MemoryStream ms    = new System.IO.MemoryStream();
        System.Drawing.Image   myimg = BarCodeHelper.DrawImg39(num, w, h, lb_s);
        myimg.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        Response.ClearContent();
        Response.ContentType = "image/Gif";
        Response.BinaryWrite(ms.ToArray());
        Response.End();
    }
Пример #38
0
    /// <summary>
    /// 发送post请求,返回图片二进制数组,页面采用 Response.BinaryWrite(byteStream)方法输出图片
    /// </summary>
    /// <param name="postUrl">请求的URL</param>
    /// <param name="postData">post的数据</param>
    /// <returns></returns>
    public static byte[] PostReturnImgArrary(string postUrl, string postData)
    {
        Encoding       encoding = Encoding.GetEncoding("utf-8");
        HttpWebRequest Request  = (HttpWebRequest)WebRequest.Create(postUrl);

        Request.Method            = "POST";
        Request.ContentType       = "application/x-www-form-urlencoded";
        Request.AllowAutoRedirect = true;
        byte[] postdata = encoding.GetBytes(postData);
        using (Stream newStream = Request.GetRequestStream())
        {
            newStream.Write(postdata, 0, postdata.Length);
        }
        using (HttpWebResponse response = (HttpWebResponse)Request.GetResponse())
        {
            Stream stream            = response.GetResponseStream();
            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
            MemoryStream         ms  = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return(ms.ToArray());
        }
    }
Пример #39
0
    /// <summary>
    /// 将请求的数据保存到指定的文件路径
    /// </summary>
    /// <param name="type">post,get</param>
    /// <param name="requestPath">请求的路径http://xxx.test.com/getfile.aspx</param>
    /// <param name="postData">post的数据</param>
    /// <param name="filePath">d:\dlwonload</param>
    public static void NetRequestToFile(string type, string requestPath, string postData, string filePath)
    {
        System.Net.WebRequest request = System.Net.WebRequest.Create(requestPath);
        Encoding encoding             = Encoding.GetEncoding("utf-8");

        if (type.ToUpper() == "POST")
        {
            request.Method = "POST";
            byte[] postdata = encoding.GetBytes(postData);
            using (Stream newStream = request.GetRequestStream())
            {
                newStream.Write(postdata, 0, postdata.Length);
            }
        }
        using (System.Net.WebResponse response = request.GetResponse())
        {
            Stream stream   = response.GetResponseStream();
            string fileName = filePath + DateTime.Now.ToString("yyyyMMddhhmmss") + ".";
            if (response.ContentType.IndexOf("image") > -1)
            {
                fileName += response.ContentType.Split('/')[1];
                System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                MemoryStream         ms  = new MemoryStream();
                img.Save(fileName);
            }
            else
            {
                fileName += "html";
                StreamReader streamreader = new System.IO.StreamReader(stream, System.Text.Encoding.GetEncoding("utf-8"));
                string       content      = streamreader.ReadToEnd();
                using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8))
                {
                    sw.WriteLine(content);
                    sw.Flush();
                    sw.Close();
                }
            }
        }
    }
Пример #40
0
    protected void UploadBtn_Click(object sender, EventArgs e)
    {
        if (picUpload.FileName.Contains(".jpg"))
        {
            string CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            string filePath         = CurrentDirectory + "proPics\\Det" + bizNum + "_" + imgID + ".jpg";
            picUpload.SaveAs(filePath);

            using (System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(filePath))
            {
                System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(dummyfalse);
                System.Drawing.Image thumbSizeImg = fullSizeImg.GetThumbnailImage(73, 43, dummyCallBack, IntPtr.Zero);
                thumbSizeImg.Save(filePath.Replace("Det", "Thumbs\\t"), System.Drawing.Imaging.ImageFormat.Jpeg);
                thumbSizeImg.Dispose();
            }
            Response.Redirect("AddBiz.aspx?cat=" + Request.QueryString["cat"] + "&sub=" + Request.QueryString["sub"] + "&BizID=" + Request.QueryString["BizID"] + "&tab=5");
        }
        else
        {
            errMsg.Text = "הקובץ חייב להיות מסוג JPG";
        }
    }
Пример #41
0
    public static void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
    {
        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (OnlyResizeIfWider)
        {
            if (FullsizeImage.Width <= NewWidth)
            {
                //this is also for change automaticaly fix the width of the image
                NewWidth = FullsizeImage.Width;
                //  NewWidth = 150;
            }
        }

        //this is automatically fix the height of the image
        int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;

        //     int NewHeight = 170;
        if (NewHeight > MaxHeight)
        {
            // Resize with height instead
            //this is automatically fix the width of the image
            NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
            // NewWidth = 150;
            NewHeight = MaxHeight;
        }

        System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

        // Clear handle to original file so that we can overwrite it if necessary
        FullsizeImage.Dispose();

        // Save resized picture
        NewImage.Save(NewFile);
    }
Пример #42
0
    static IEnumerator WaitForImage(FileInfo fileInfo, Action <ResultBean> callBack)
    {
        System.Drawing.Image image     = null;
        System.Drawing.Image image_Gai = null;
        // 开个线程
        new Thread(() =>
        {
            image          = System.Drawing.Image.FromFile(fileInfo.FullName);
            int saveWidth  = image.Width;
            int saveHeight = image.Height;
            GetShouFan(ref saveWidth, ref saveHeight);
            image_Gai = image.GetThumbnailImage(saveWidth, saveHeight, () => false, System.IntPtr.Zero);
        }).Start();
        while (null == image)
        {
            yield return(0);
        }
        while (null == image_Gai)
        {
            yield return(0);
        }
        using (MemoryStream ms = new MemoryStream())
        {
            image_Gai.Save(ms, ImageFormat.Png);
            yield return(0);

            Texture2D tex = new Texture2D(8, 8);
            tex.LoadImage(ms.ToArray());
            yield return(0);

            Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
            sp.name = Path.GetFileNameWithoutExtension(fileInfo.FullName);
            if (null != callBack)
            {
                ResultBean result = new ResultBean(sp, fileInfo, image.Width, image.Height);
                callBack(result);
            }
        }
    }
    private MemberSuiteFile getImageFile()
    {
        if (!imageUpload.HasFile)
        {
            return(null);
        }

        MemoryStream stream = new MemoryStream(imageUpload.FileBytes);

        System.Drawing.Image image = Image.FromStream(stream);

        //Resize the image if required - perserve scale
        if (image.Width > 120 || image.Height > 120)
        {
            int     largerDimension = image.Width > image.Height ? image.Width : image.Height;
            decimal ratio           = largerDimension / 120m;            //Target size is 120x120 so this works for either dimension

            int thumbnailWidth  = Convert.ToInt32(image.Width / ratio);  //Explicit convert will round
            int thumbnailHeight = Convert.ToInt32(image.Height / ratio); //Explicit convert will round

            //Create a thumbnail to resize the image.  The delegate is not used and IntPtr.Zero is always required.
            //For more information see http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx
            Image resizedImage = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight, () => false, IntPtr.Zero);

            //Replace the stream containing the original image with the resized image
            stream = new MemoryStream();
            resizedImage.Save(stream, image.RawFormat);
        }

        var result = new MemberSuiteFile
        {
            FileContents = stream.ToArray(),
            FileName     = imageUpload.FileName,
            FileType     = imageUpload.PostedFile.ContentType
        };

        return(result);
    }
Пример #44
0
    public void GerarThumbnail(string filename, string sPath, string PathFinal)
    {
        // get the file name -- fall800.jpg

        // create an image object, using the filename we just retrieved
        System.Drawing.Image image = System.Drawing.Image.FromFile(sPath);

        // create the actual thumbnail image
        System.Drawing.Image thumbnailImage = image.GetThumbnailImage(100, 100, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

        // make a memory stream to work with the image bytes
        MemoryStream imageStream = new MemoryStream();

        // put the image into the memory stream
        thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

        // make byte array the same size as the image
        byte[] imageContent = new Byte[imageStream.Length];

        // rewind the memory stream
        imageStream.Position = 0;

        // load the byte array with the image
        imageStream.Read(imageContent, 0, (int)imageStream.Length);

        // return byte array to caller with image type
        //Response.ContentType = "image/png";

        // Create the file.

        string timestamp = Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Minute) + Convert.ToString(DateTime.Now.Second) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Month) + Convert.ToString(DateTime.Now.Year);

        using (System.IO.FileStream fs = System.IO.File.Create(Server.MapPath(PathFinal) + timestamp + ".png"))
        {
            // Add some information to the file.
            fs.Write(imageContent, 0, imageContent.Length);
        }
    }
Пример #45
0
    public ReturnData AJAX_Update_ShopInfo(string shop_email, string shop_city, string shop_address, string shop_phone, string shop_email_logo, string baseImage)
    {
        try
        {
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                db.TBConfigurations.Where(x => x.Name.Contains("shop_email")).FirstOrDefault().Value   = shop_email;
                db.TBConfigurations.Where(x => x.Name.Contains("shop_city")).FirstOrDefault().Value    = shop_city;
                db.TBConfigurations.Where(x => x.Name.Contains("shop_address")).FirstOrDefault().Value = shop_address;
                db.TBConfigurations.Where(x => x.Name.Contains("shop_phone")).FirstOrDefault().Value   = shop_phone;


                if (baseImage != "" && shop_email_logo != "")
                {
                    var      logo = db.TBConfigurations.Where(x => x.Name.Contains("shop_email_logo")).FirstOrDefault();
                    FileInfo fi   = new FileInfo(HttpContext.Current.Server.MapPath("/assets/images/email_logo/" + logo.Value));
                    if (fi.Exists)
                    {
                        fi.Delete();
                    }
                    logo.Value = "email_logo" + WITLibrary.ConvertCustom.GetExtention(shop_email_logo);
                    System.Drawing.Image _image = WITLibrary.ConvertCustom.Base64ToImage(baseImage);
                    _image.Save(HttpContext.Current.Server.MapPath("/assets/images/email_logo/" + logo.Value));
                }

                db.SubmitChanges();

                return(ReturnData.MessageSuccess("Shop information has been updated successfully.", null));
            }
        }
        catch (Exception ex)
        {
            Class_Log_Error log = new Class_Log_Error();
            log.Insert(ex.Message, ex.StackTrace);

            return(ReturnData.MessageFailed(ex.Message, null));
        }
    }
Пример #46
0
    protected void QRCodeOlustur()
    {
        RadBarcode barcode = new RadBarcode();

        //barcode.Text = "some text";
        barcode.Text      = "";
        barcode.Type      = BarcodeType.QRCode;
        barcode.LineWidth = 2;
        RadBinaryImage image = new RadBinaryImage();

        //PlaceHolder1.Controls.Add(image);
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        barcode.GetImage().Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        image.DataValue = stream.ToArray();



        System.Drawing.Image img = barcode.GetImage();
        string qrCodeImageFile   = Guid.NewGuid().ToString();

        img.Save(Server.MapPath("~/DosyaSistemi/QRCode/" + qrCodeImageFile + ".png"), System.Drawing.Imaging.ImageFormat.Png);
        //FileStream file =new FileStream(Server.MapPath("~/DosyaSistemi/Oneri.docx"))
    }
Пример #47
0
    /// <summary>
    /// 在图片上添加文字水印
    /// </summary>
    /// <param name="path">要添加水印的图片路径</param>
    /// <param name="syPath">生成的水印图片存放的位置</param>
    public static void AddWaterWord(Stream path, string syPath,float x,float y,string syWord)
    {
       
        System.Drawing.Image image = System.Drawing.Image.FromStream(path);

        //新建一个画板
        System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(image);
        graphic.DrawImage(image, 0, 0, image.Width, image.Height);

        //设置字体
        System.Drawing.Font f = new System.Drawing.Font("PingFang SC", 28);

        //设置字体颜色
        System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

        graphic.DrawString(syWord, f, b, x, y);
        graphic.Dispose();

        //保存文字水印图片
        image.Save(syPath);
        image.Dispose();

    }
Пример #48
0
    protected void add_Click(object sender, EventArgs e)
    {
        if (real1.HasFiles)
        {
            byte[] data = real1.FileBytes;

            MemoryStream         stream = new MemoryStream(data);
            System.Drawing.Image image  = System.Drawing.Image.FromStream(stream);

            string guid = Guid.NewGuid().ToString().Replace("-", "");
            string path = @"C:\sites\ru.dsoft.hwa\Files\" + guid + ".png";
            image.Save(path, System.Drawing.Imaging.ImageFormat.Png);

            stream.Close();
            stream.Dispose();
            image.Dispose();

            string expression = "insert photos values ('" + guid + "', @email, '" + path + "', @description)";
            Service.Exec_command(expression, "@email", email, "@description", Cookie.Text);

            Response.Redirect("loged.aspx");
        }
    }
Пример #49
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int personId = Int32.Parse(Request.QueryString["PersonId"]);
        int ySize    = 0;

        string ySizeString = Request.QueryString["YSize"];

        if (!String.IsNullOrEmpty(ySizeString))
        {
            ySize = Int32.Parse(ySizeString);
        }
        int cacheLength = (personId % 10) * 100 + 500;

        Response.Cache.SetExpires(DateTime.Now.AddSeconds(cacheLength));

        Response.ContentType = "image/jpeg";

        string cacheDataKey = "PersonPhoto-" + personId.ToString() + "-" + ySize.ToString();

        System.Drawing.Image photo = (System.Drawing.Image)Cache.Get(cacheDataKey);

        if (photo == null)
        {
            photo = GetScaledPortrait(personId, ySize);

            // Cache for a different time for different people, so they don't expire
            // all at the same time

            Cache.Insert(cacheDataKey, photo, null, DateTime.Today.AddSeconds(personId + 3600).ToUniversalTime(), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        using (Stream responseStream = Response.OutputStream)
        {
            photo.Save(responseStream, ImageFormat.Jpeg);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Response.BinaryWrite((byte[])Session["ImageToCrop"]);
        }
        catch (Exception)
        {
            try
            {
                System.Drawing.Image ImgError       = System.Drawing.Image.FromFile(Server.MapPath("../Resources/nophotoUploded.gif"));
                MemoryStream         NewImageStream = new MemoryStream();
                ImgError.Save(NewImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                ImgError.Dispose();

                //returning the Croped image as byte stream
                Response.BinaryWrite(NewImageStream.GetBuffer());
            }
            catch (Exception Ex)
            {
                ErrorLog.WriteErrorLog("Member  Image", Ex);
            }
        }
    }
Пример #51
0
 protected void Page_Load(object sender, EventArgs e)
 {
     thisRm = Session["Room"] as room;
     System.Drawing.Image mainImage = thisRm.getMainPic;
     roomNMELBL.Text = thisRm.ToString();
     url             = "~/TempImages/" + Path.GetRandomFileName();
     url             = Path.ChangeExtension(url, ".jpg");
     mainImage.Save(Server.MapPath(url));
     rmPC.ImageUrl = url;
     descTXT.Text  = thisRm.description;
     priceLBL.Text = "$" + string.Format("{0:0.00}", thisRm.getAskedPrice.ToString());
     if (Session["User"] is customer)
     {
         LinkButton newBtn = new LinkButton();
         newBtn.Text   = "(" + thisRm.roomHotel.getName + ")";
         newBtn.Click += (a, t) =>
         {
             Session["Hotel"] = thisRm.roomHotel;
             Response.Redirect("~//HotPGE.aspx");
         };
         hotelLBL.Text = string.Empty;
         hotelLBL.Controls.Add(newBtn);
         theUser = Session["User"] as customer;
         setupCustomer();
     }
     else if (Session["User"] is hotel)
     {
         hotelLBL.Text = "(" + thisRm.roomHotel.getName + ")";
         theUser       = Session["User"] as hotel;
         setupHotel((theUser as hotel).returnId == thisRm.roomHotel.returnId);
     }
     else
     {
         subtractOffers();
     }
 }
Пример #52
0
 protected void btnUpload_Click(object sender, EventArgs e)
 {
     try
     {
         if (this.fuImage.HasFile)
         {
             if (CheckAuthentication())
             {
                 string fileName = this.fuImage.FileName;
                 if (PictureManager.ValidImageExtension(fileName))
                 {
                     string          strSaveLocation = Path.Combine(physicalpath, fileName);
                     string          strExtension    = Path.GetExtension(HttpContext.Current.Request.Files[0].FileName).ToLower();
                     SageFrameConfig config          = new SageFrameConfig();
                     string          extension       = config.GetSettingValueByIndividualKey(SageFrameSettingKeys.FileExtensions);
                     this.fuImage.SaveAs(strSaveLocation);
                     System.Drawing.Image image    = System.Drawing.Image.FromFile(strSaveLocation);
                     System.Drawing.Image thumbImg = image.GetThumbnailImage(125, 100, null, new IntPtr());
                     if (File.Exists(physicalpath + @"\thumb\" + fileName))
                     {
                         File.Delete(physicalpath + @"\thumb\" + fileName);
                     }
                     thumbImg.Save(physicalpath + @"\thumb\" + fileName);
                     ImageFiles.Add(new ImageFile {
                         ThumbImageFileName = thumbpath + @"/" + fileName, FileName = path + @"/" + fileName, Size = (this.fuImage.FileBytes.Length / 1024).ToString(), CreatedDate = DateTime.Now.ToString()
                     });
                     ImageFiles = ImageFiles.OrderByDescending(x => DateTime.Parse(x.CreatedDate)).ToList();
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Пример #53
0
    private List <byte[]> GetBytesFromImage(System.Drawing.Image image)
    {
        List <byte[]> tex = new List <byte[]>();

        if (image != null)
        {
            FrameDimension frame = new FrameDimension(image.FrameDimensionsList[0]);
            //获取维度帧数
            int frameCount = image.GetFrameCount(frame);
            for (int i = 0; i < frameCount; ++i)
            {
                image.SelectActiveFrame(frame, i);
                using (MemoryStream stream = new MemoryStream())
                {
                    image.Save(stream, ImageFormat.Png);
                    byte[] data = new byte[stream.Length];
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Read(data, 0, Convert.ToInt32(stream.Length));
                    tex.Add(data);
                }
            }
        }
        return(tex);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        ImageVerifier.ServiceClient imgPxy = new ImageVerifier.ServiceClient();
        string myStr, userLen;

        if (Session["userLength"] == null)
        {
            userLen = "4";
        }
        else
        {
            userLen = Session["userLength"].ToString();
        }
        myStr = imgPxy.GetVerifierString(userLen);
        Session["generatedString"] = myStr;


        Stream myStream = imgPxy.GetImage(myStr);

        System.Drawing.Image myImage = System.Drawing.Image.FromStream(myStream);
        Response.ContentType = "image/jpeg";
        myImage.Save(Response.OutputStream, ImageFormat.Jpeg);
    }
Пример #55
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["uname"] == null && !Request.Path.EndsWith("login.aspx"))
        {
            Response.Redirect("login.aspx");
        }
        else
        {
            if (IsPostBack)
            {
                try
                {
                    string seller = Request.Form["tbid"].ToString();


                    if (seller.Length > 0)
                    {
                        seller = seller.Replace("data:image/jpeg;base64,", "");


                        byte[]       sellerBytes = Convert.FromBase64String(seller);
                        MemoryStream ms          = new MemoryStream(sellerBytes, 0, sellerBytes.Length);
                        ms.Write(sellerBytes, 0, sellerBytes.Length);
                        System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
                        image.Save(Server.MapPath("/Captures/Buyer.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
                        //************************************************
                        ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }
    }
Пример #56
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["imgMain"] != null)
        {
            try
            {
                string imgMain = Server.MapPath("~/Images/TerrorPhoto/" + Request["imgMain"].ToString());
                byte[] bt      = File.ReadAllBytes(imgMain);

                MemoryStream strm = new MemoryStream();
                strm.Write(bt, 0, bt.Length);
                System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
                double width             = img.Width;
                double height            = img.Height;
                int    thumb_w           = 100;
                int    thumb_h           = Convert.ToInt32((height / width) * thumb_w);
                img = img.GetThumbnailImage(thumb_w, thumb_h, null, new IntPtr());
                img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch
            {
            }
        }
    }
Пример #57
0
    protected void btn_OK_Click(object sender, EventArgs e)
    {
        #region 帖子的回复

        #region 添加帖子的回复
        BBS_ForumReplyBLL replybll = new BBS_ForumReplyBLL();
        replybll.Model.ItemID    = Convert.ToInt32(ViewState["ItemID"]);
        replybll.Model.Title     = Title.Value;
        replybll.Model.Content   = ckedit_content.Text;
        replybll.Model.Replyer   = Session["UserName"].ToString();
        replybll.Model.ReplyTime = DateTime.Now;
        replybll.Model.IPAddress = Request.ServerVariables.Get("REMOTE_ADDR").ToString();
        int replyid = replybll.Add();    // 返回已经回复的帖子的ID

        //修改论坛文章的留言量
        BBS_ForumItemBLL itembll = new BBS_ForumItemBLL(Convert.ToInt32(ViewState["ItemID"]));
        itembll.UpdateAddReplyTimes(Convert.ToInt32(ViewState["ItemID"]));
        #endregion

        #region 添加留言的附件
        ArrayList upattlist = (ArrayList)ViewState["UpattList"];
        if (upattlist != null && upattlist.Count > 0)
        {
            foreach (BBS_ForumAttachment att in upattlist)
            {
                string path = att.Path;
                if (path.StartsWith("~"))
                {
                    path = Server.MapPath(path);
                }
                FileStream stream = new FileStream(path, FileMode.Open);
                byte[]     buff   = new byte[stream.Length];
                stream.Read(buff, 0, buff.Length);
                stream.Close();
                att.Path   = "";
                att.ItemID = (int)ViewState["ItemID"];

                #region 自动压缩上传的图片
                if (ATMT_AttachmentBLL.IsImage(att.ExtName))
                {
                    try
                    {
                        MemoryStream         s             = new MemoryStream(buff);
                        System.Drawing.Image originalImage = System.Drawing.Image.FromStream(s);
                        s.Close();

                        int width = originalImage.Width;

                        if (width > 1024 || att.ExtName == "bmp")
                        {
                            if (width > 1024)
                            {
                                width = 1024;
                            }

                            System.Drawing.Image thumbnailimage = ImageProcess.MakeThumbnail(originalImage, width, 0, "W");

                            MemoryStream thumbnailstream = new MemoryStream();
                            thumbnailimage.Save(thumbnailstream, System.Drawing.Imaging.ImageFormat.Jpeg);
                            thumbnailstream.Position = 0;
                            att.FileSize             = (int)(thumbnailstream.Length / 1024);
                            att.ExtName = "jpg";

                            byte[] b = new byte[thumbnailstream.Length];
                            thumbnailstream.Read(b, 0, b.Length);
                            thumbnailstream.Close();
                            buff = b;
                        }
                    }
                    catch { }
                }
                #endregion

                att.Reply = replyid;
                BBS_ForumAttachmentBLL bll = new BBS_ForumAttachmentBLL();
                bll.Model = att;
                bll.Add(buff);

                BBS_ForumAttachment m = bll.Model;
                string uploadcontent  = "";    //插入主表中

                switch (att.ExtName.ToLower())
                {
                case "jpg":
                case "gif":
                case "bmp":
                case "png":
                    uploadcontent = " [IMG]DownloadAttachfile.aspx?GUID=" + m.GUID.ToString() + "[/IMG]<br/>";
                    break;

                case "mp3":
                    uploadcontent = " [MP=320,70]DownloadAttachfile.aspx?GUID=" + m.GUID.ToString() + "[/MP]<br/>";
                    break;

                case "avi":
                    uploadcontent = " [MP=320,240]DownloadAttachfile.aspx?GUID=" + m.GUID.ToString() + "[/MP]<br/>";
                    break;

                case "swf":
                    uploadcontent = " [FLASH]DownloadAttachfile.aspx?GUID=" + m.GUID.ToString() + "[/FLASH]<br/>";
                    break;

                default:
                    uploadcontent = "<a href=DownloadAttachfile.aspx?GUID=" + m.GUID.ToString() + ">" + att.Name + "." + att.ExtName + "</a><br/>";
                    break;
                }
                ViewState["Content"] += uploadcontent + "<br/>";
            }

            if (ViewState["SavePath"] != null)
            {
                try
                {
                    string path = (string)ViewState["SavePath"];
                    path = path.Substring(0, path.LastIndexOf("\\"));
                    Directory.Delete(path, true);
                    ViewState["SavePath"] = null;
                }
                catch { }
            }

            //将附件的路径添加到回复主表中去
            replybll.Model.Content += "<br/><font color=red><b>附件列表:</b></font><br/>" + ViewState["Content"].ToString();
            replybll.Update();

            //清空附件的列表
            for (int i = upattlist.Count - 1; i >= 0; i--)
            {
                this.lbx_AttList.Items.RemoveAt(i);
                upattlist.RemoveAt(i);
            }
            ViewState["UpattList"] = upattlist;
        }
        #endregion

        #endregion

        Response.Redirect("display.aspx?ID=" + ViewState["ItemID"].ToString() + "&BoardID=" + ViewState["BoardID"].ToString());
    }
Пример #58
0
    private void LoadPeople()
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("/Content/Images/Hexagon.png"));

        MemoryStream m = new MemoryStream();

        image.Save(m, image.RawFormat);
        byte[] imageArray = m.ToArray();

        using (SqlConnection con = new SqlConnection(Connection.ConnectionString))
        {
            con.Open();
            SqlCommand command = new SqlCommand("select Users_tbl.User_ID,FirstName,Surname,Gender,Friend_ID,Description,(select Firstname from Users_tbl where User_ID = Friend_ID) as 'FriendName',(select Surname from Users_tbl where User_ID = Friend_ID) as 'FriendSurname' from Users_tbl full outer join Friends_tbl" +
                                                " on Users_tbl.User_ID = Friends_tbl.User_ID full outer join Invitation_tbl on Friends_tbl.Invitation_ID = Invitation_tbl.Invite_ID", con);
            command.ExecuteNonQuery();
            SqlDataReader reader           = command.ExecuteReader();
            List <string> friends          = new List <string>();
            List <string> sentRequests     = new List <string>();
            List <string> receivedRequests = new List <string>();
            List <User>   registeredPeople = new List <User>();
            while (reader.Read())
            {
                try                                                                            //the method will try to read a null Friend_ID and throw an exception
                {
                    if (reader.GetInt32(4) == int.Parse(Session["LoggedInUserID"].ToString())) //if current logged user is a Friend to user in database
                    {
                        try
                        {
                            if (reader.GetString(5) == "Accepted")//Invite accepted
                            {
                                LoadFriends(reader.GetInt32(0).ToString(), reader.GetString(1), reader.GetString(2));
                                friends.Add(reader.GetInt32(0).ToString());
                            }//Invite accepted
                            else if (reader.GetString(5) == "Sent")//Invite sent
                            {
                                ulPending.InnerHtml += "<li class='list-group-item list-group-item-action' style='color: #7c2020'>" +
                                                       "<a href='#' >" +
                                                       "<img ID='NavPhoto" + reader.GetInt32(4) + "' class='border-light rounded rounded-circle text-center' src='data:image/" + image.GetType().ToString() + ";base64," + Convert.ToBase64String(imageArray) + "' style='background-color:white; Width:50px; Height:50px; margin-right:10px' />" +
                                                       reader.GetString(1) + " " + reader.GetString(2) +
                                                       "<span class='float-right fas  fa-check' style='color:green'></span></a>" +
                                                       "</li>";
                                sentRequests.Add(reader.GetInt32(0).ToString());
                            }//Invite sent
                             //else if (reader.GetString(5) == "Received")//Invite received
                             //{
                             //    LoadReceivedInvites(reader.GetInt32(0).ToString(), reader.GetString(1), reader.GetString(2));

                            //}//Invite received else
                        }
                        catch
                        {
                            try
                            {
                                if (reader.GetInt32(0) != int.Parse(Session["LoggedInUserID"].ToString()) &&
                                    !friends.Contains(reader.GetInt32(0).ToString()) &&
                                    !registeredPeople.Select(p => p.User_ID).Contains(reader.GetInt32(0)) &&
                                    !sentRequests.Contains(reader.GetInt32(0).ToString()) &&
                                    !receivedRequests.Contains(reader.GetInt32(0).ToString()))
                                {
                                    registeredPeople.Add(new User()
                                    {
                                        User_ID = reader.GetInt32(0), FirstName = reader.GetString(1), Surname = reader.GetString(2)
                                    });
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    else if (reader.GetInt32(0) == int.Parse(Session["LoggedInUserID"].ToString()))                       //if current logged user is a Friend to user in database
                    {
                        if (reader.GetString(5) == "Sent")                                                                //Invite was sent to logged in user i.e Received
                        {
                            LoadReceivedInvites(reader.GetInt32(4).ToString(), reader.GetString(6), reader.GetString(7)); //hence we load it in the received list
                            receivedRequests.Add(reader.GetInt32(4).ToString());
                        }//Invite accepted
                         //else if (reader.GetString(5) == "Sent")//Invite sent
                         //{
                         //    ulPending.InnerHtml += "<li class='list-group-item list-group-item-action' style='color: #7c2020'>" +
                         //                           "<a href='#' >" +
                         //                           "<img ID='NavPhoto" + reader.GetInt32(4) + "' class='border-light rounded rounded-circle text-center' src='data:image/" + image.GetType().ToString() + ";base64," + Convert.ToBase64String(imageArray) + "' style='background-color:white; Width:50px; Height:50px; margin-right:10px' />" +
                         //                           reader.GetString(1) + " " + reader.GetString(2) +
                         //                           "<span class='float-right fas  fa-check' style='color:yellow'></span></a>" +
                         //                           "</li>";

                        //}//Invite sent
                        else if (reader.GetString(5) == "Accepted")//Invite received
                        {
                            LoadFriends(reader.GetInt32(4).ToString(), reader.GetString(6), reader.GetString(7));
                            friends.Add(reader.GetInt32(4).ToString());
                        }//Invite received else
                    }
                    else
                    {
                        try
                        {
                            if (reader.GetInt32(0) != int.Parse(Session["LoggedInUserID"].ToString()) &&
                                !friends.Contains(reader.GetInt32(0).ToString()) &&
                                !registeredPeople.Select(p => p.User_ID).Contains(reader.GetInt32(0)) &&
                                !sentRequests.Contains(reader.GetInt32(0).ToString()) &&
                                !receivedRequests.Contains(reader.GetInt32(0).ToString()))
                            {
                                registeredPeople.Add(new User()
                                {
                                    User_ID = reader.GetInt32(0), FirstName = reader.GetString(1), Surname = reader.GetString(2)
                                });
                            }
                        }
                        catch
                        {
                        }
                    }
                }//Null Friend_ID try
                catch //skip
                {
                    try
                    {
                        if (reader.GetInt32(0) != int.Parse(Session["LoggedInUserID"].ToString()) &&
                            !friends.Contains(reader.GetInt32(0).ToString()) &&
                            !registeredPeople.Select(p => p.User_ID).Contains(reader.GetInt32(0)) &&
                            !sentRequests.Contains(reader.GetInt32(0).ToString()) &&
                            !receivedRequests.Contains(reader.GetInt32(0).ToString()))
                        {
                            registeredPeople.Add(new User()
                            {
                                User_ID = reader.GetInt32(0), FirstName = reader.GetString(1), Surname = reader.GetString(2)
                            });
                        }
                    }
                    catch//skip
                    {
                    }
                }
            }//while

            reader.Close();
            con.Close();

            foreach (string userid in registeredPeople.Select(p => p.User_ID.ToString()).Except(friends).Except(sentRequests).Except(receivedRequests).ToList())
            {
                User user = registeredPeople.SingleOrDefault(u => u.User_ID == int.Parse(userid));
                LoadRegisteredPeople(user.User_ID.ToString(), user.FirstName, user.Surname);
            }
        }
    }
Пример #59
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get physical path from url
        string physicalImagePath = Request.QueryString["path"];
        // Get display moden
        DisplayModes mode = DisplayModes.Thumbnail;

        if (Request.QueryString["mode"] != null && Request.QueryString["mode"].Trim().ToUpper() == "FULL")
        {
            mode = DisplayModes.Full;
        }

        // Check path
        if (physicalImagePath == null || physicalImagePath.Length == 0 || !File.Exists(physicalImagePath))
        {
            // If can not get the path or get a empty path or get a wrong path, then do noting
            return;
        }

        if (mode != DisplayModes.Full && Holder.ContainsPhysicalImagePath(physicalImagePath))
        {
            try
            {
                using (MemoryStream imageStream = new MemoryStream())
                {
                    // Set thumbnail quality
                    EncoderParameters encoderPara = new EncoderParameters(1);
                    encoderPara.Param[0] = new EncoderParameter(Encoder.Quality, Convert.ToInt64(Consts.ThumbnailImageQuality));
                    ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(Consts.ThumbnailImageMimeType);

                    // Put image to the temp space with jpg format
                    Holder.GetImageByPhysicalImagePath(physicalImagePath).Save(imageStream, imageCodecInfo, encoderPara);
                    // Clear the reponse buffer
                    Response.Clear();
                    // Set the http stream as a jpg file
                    Response.ContentType = Consts.ThumbnailImageMimeType;
                    // Put the image stream to the http stream from temp space from Holder
                    imageStream.WriteTo(Response.OutputStream);
                }
                return;
            }
            catch (Exception ex_)
            {
                // do nothing
                ;
            }
        }

        // Temp space for the image file
        using (MemoryStream imageStream = new MemoryStream())
        {
            try
            {
                // Load image file from physical disk
                System.Drawing.Image image = System.Drawing.Image.FromFile(physicalImagePath);

                if (mode == DisplayModes.Full)
                {
                    using (FileStream fs = new FileStream(physicalImagePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, Convert.ToInt32(fs.Length));

                        // Clear the reponse buffer
                        Response.Clear();
                        // Set the http stream as a jpg file
                        Response.ContentType = Consts.ThumbnailImageMimeType;
                        // Put the image stream to the http stream from temp space
                        Response.BinaryWrite(buffer);
                    }
                }
                else
                {
                    using (Stream bmpImage = new MemoryStream())
                    {
                        if (!Consts.UseExifThumbnailImage)
                        {
                            // Reload image as BitMap format
                            // The JPG file which with EXIF format maybe include a ThumbnailImage
                            image.Save(bmpImage, ImageFormat.Bmp);
                            image = System.Drawing.Image.FromStream(bmpImage);
                        }

                        //init thumbnail object
                        System.Drawing.Image imageThumbnail = null;

                        // Get the thumbnail image
                        imageThumbnail = image.GetThumbnailImage(Consts.ThumbnailImageWidth,
                                                                 Convert.ToInt32((Convert.ToDouble(Consts.ThumbnailImageWidth) / image.Width) * image.Height),
                                                                 new System.Drawing.Image.GetThumbnailImageAbort(ReturnFalse),
                                                                 IntPtr.Zero);
                        // Save to Holder
                        Holder.AddImage(physicalImagePath, imageThumbnail);

                        // Set thumbnail quality
                        EncoderParameters encoderPara = new EncoderParameters(1);
                        encoderPara.Param[0] = new EncoderParameter(Encoder.Quality, Convert.ToInt64(Consts.ThumbnailImageQuality));
                        ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(Consts.ThumbnailImageMimeType);

                        // Put image to the temp space with jpg format
                        imageThumbnail.Save(imageStream, imageCodecInfo, encoderPara);

                        // Clear the reponse buffer
                        Response.Clear();
                        // Set the http stream as a jpg file
                        Response.ContentType = Consts.ThumbnailImageMimeType;
                        // Put the image stream to the http stream from temp space
                        imageStream.WriteTo(Response.OutputStream);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.StackTrace);
                // If any exception be throwed, then do nothing
                return;
            }
        }
    }
Пример #60
-1
		private static void SaveImage(Image image, Stream stream)
		{
			if (Codecs.Contains(image.RawFormat.Guid))
				image.Save(stream, image.RawFormat);
			else
				image.Save(stream, ImageFormat.Png);
		}