/// <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;
     }
 }
Example #2
0
	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);
	}
Example #3
0
 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);
 }
Example #4
0
 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());
 }
Example #5
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();
 }
Example #6
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 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();
	}
Example #8
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)
            {

            }
        }
        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();
            }
        }
Example #10
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);
        }
Example #11
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;
            }
Example #12
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;
        }
Example #13
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);
 }
Example #14
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);
 }
Example #15
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);
        }
Example #16
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);
 }
Example #17
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();
        }
 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());
         }
     }
 }
Example #19
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);
        }
Example #20
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();
        }
Example #21
0
        public static string CaptureAndPost(Image img)
        {
            //string uploadurl = "http://yfrog.com/api/upload";
            string twitusername = "feedtoby";
            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;
        }
Example #22
0
File: Utils.cs Project: kekse/Look
        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;
        }
        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);
            }
        }
Example #24
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;
        }
 public byte[] ImageToByteArray(Image imageIn, string imageFormatString)
 {
     var ms = new MemoryStream();
     var imageFormat = getImageFormat(imageFormatString);
     imageIn.Save(ms, imageFormat);
     return ms.ToArray();
 }
Example #26
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);
     }
 }
        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;
        }
        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);
            }
        }
Example #29
0
 public static Stream ImageToStream(Image image, ImageFormat formaw)
 {
     var stream = new MemoryStream();
     image.Save(stream, formaw);
     stream.Position = 0;
     return stream;
 }
        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();
            }
        }