private string GetRelativeUrl(IEntryImageInformation picture, ImageSize size) {
			if (picture.Version > 0) {
				return string.Format("/img/{0}/main{1}/{2}{3}?v={4}", picture.EntryType.ToString().ToLowerInvariant(), GetDir(size), picture.Id, 
					ImageHelper.GetExtensionFromMime(picture.Mime), picture.Version);
			} else
				return string.Format("/img/{0}/main{1}/{2}{3}", picture.EntryType.ToString().ToLowerInvariant(), GetDir(size), picture.Id, ImageHelper.GetExtensionFromMime(picture.Mime));
		}
Пример #2
0
        public static string GetProjectImage(string projectId, ImageSize imageType = ImageSize.Normal)
        {
            using (var session = MvcApplication.Store.OpenSession())
            {
                using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(1000)))
                {
                    var project = session.Load<Project>(projectId);

                    if (project == null)
                        return NOIMAGE_URL;

                    if (project.Image == null)
                        return NOIMAGE_URL;

                    switch (imageType)
                    {
                        case ImageSize.Normal:
                            return string.IsNullOrEmpty(project.Image.Logo) ? NOIMAGE_URL : project.Image.Logo;
                        case ImageSize.Icon:
                            return string.IsNullOrEmpty(project.Image.Icon) ? NOIMAGE_URL : project.Image.Icon;
                        case ImageSize.Banner:
                            return string.IsNullOrEmpty(project.Image.Banner) ? NOIMAGE_URL : project.Image.Banner;
                        case ImageSize.BannerThumb:
                            return string.IsNullOrEmpty(project.Image.Banner) ? NOIMAGE_BANNER : project.Image.Thumbnail;
                    }
                }
            }

            return NOIMAGE_URL;
        }
Пример #3
0
        /// <summary>
        /// Download image.
        /// </summary>
        /// <param name="imagePath">The image path.</param>
        /// <param name="imageExtension">The image extension.</param>
        /// <param name="imageSize">The image size.</param>
        /// <param name="callback">The callback.</param>
        /// <returns>A coroutine.</returns>
        public IEnumerator DownloadImage(
            string imagePath,
            string imageExtension,
            ImageSize imageSize,
            Action<IResult<Texture2D>> callback)
        {
            string imageSizeURIPart = this.GetImageSize(imageSize);
            string requestUri = string.Concat(imagePath, "/", imageSizeURIPart, ".", imageExtension);

            WWW request = this.webRequestor.PerformGetRequest(requestUri);

            yield return request;

            IResult<Texture2D> result = null;

            if (request != null &&
                string.IsNullOrEmpty(request.error))
            {
                result = new Result<Texture2D>(request.texture);
            }
            else
            {
                result = new Result<Texture2D>(request.error);
            }

            callback(result);
        }
        public Task<byte[]> GetDeviceImageAsync(string id, ImageSize size = ImageSize.Small)
        {
            if (string.IsNullOrEmpty(id))
                throw new ArgumentException("Device id is required");

            string action = Map[typeof(Device)];
            var request = GetRequest(Request(action, id, "image"), Method.GET);
            request.AddParameter("size", size);

            var tcs = new TaskCompletionSource<byte[]>();
            try
            {
                RestClient.ExecuteAsync(request, response =>
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                            tcs.SetResult(response.RawBytes);
                        else
                            tcs.SetResult(null);
                    });
            }
            catch(Exception ex)
            {
                tcs.SetException(ex);
            }
            return tcs.Task;
        }
Пример #5
0
 public static MvcHtmlString ProductImage(this HtmlHelper helper, string rawFile, ImageSize size, bool noCaching, object htmlAttributes)
 {
     var imgSizeIndicator = System.Enum.GetName(typeof(ImageSize), size);
     var imgFile = UrlHelper.GenerateContentUrl(string.Format("~/Images/Products/{0}", rawFile), helper.ViewContext.HttpContext);
     TagBuilder tb = new TagBuilder("img");
     if (noCaching)
         tb.MergeAttribute("src", imgFile + "?" + new Random().NextDouble().ToString(CultureInfo.InvariantCulture));
     else
         tb.MergeAttribute("src", imgFile);
     tb.MergeAttribute("border", "0");
     var sizeValue = 65;
     switch (size)
     {
         case ImageSize.Medium:
             sizeValue = 130;
             break;
         case ImageSize.Large:
             sizeValue = 195;
             break;
         default:
             break;
     }
     tb.MergeAttribute("width", sizeValue.ToString());
     tb.MergeAttribute("height", sizeValue.ToString());
     if (htmlAttributes != null)
     {
         IDictionary<string, object> additionAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
         tb.MergeAttributes<string, object>(additionAttributes);
     }
     return MvcHtmlString.Create(tb.ToString(TagRenderMode.SelfClosing));
 }
        /// <summary>
        /// Returns an URL to entry thumbnail image.
        /// Currently only used for album and artist main images.
        /// 
        /// Gets the URL to the static images folder on disk if possible,
        /// otherwise gets the image from the DB.
        /// </summary>
        /// <param name="urlHelper">URL helper. Cannot be null.</param>
        /// <param name="imageInfo">Image information. Cannot be null.</param>
        /// <param name="size">Requested image size.</param>
        /// <param name="fullUrl">
        /// Whether the URL should always include the hostname and application path root.
        /// If this is false (default), the URL maybe either full (such as http://vocadb.net/Album/CoverPicture/123)
        /// or relative (such as /Album/CoverPicture/123).
        /// Usually this should be set to true if the image is to be referred from another domain.
        /// </param>
        /// <returns>URL to the image thumbnail.</returns>
        public static string ImageThumb(this UrlHelper urlHelper, IEntryImageInformation imageInfo, ImageSize size, bool fullUrl = false)
        {
            if (imageInfo == null)
                return null;

            var shouldExist = ShouldExist(imageInfo);
            string dynamicUrl = null;

            // Use MVC dynamic actions when requesting original or an image that doesn't exist on disk.
            if (imageInfo.EntryType == EntryType.Album) {

                if (size == ImageSize.Original)
                    dynamicUrl = urlHelper.Action("CoverPicture", "Album", new { id = imageInfo.Id, v = imageInfo.Version });
                else if (shouldExist && !imagePersister.HasImage(imageInfo, size))
                    dynamicUrl = urlHelper.Action("CoverPictureThumb", "Album", new { id = imageInfo.Id, v = imageInfo.Version });

            } else if (imageInfo.EntryType == EntryType.Artist) {

                if (size == ImageSize.Original)
                    dynamicUrl = urlHelper.Action("Picture", "Artist", new { id = imageInfo.Id, v = imageInfo.Version });
                else if (shouldExist && !imagePersister.HasImage(imageInfo, size))
                    dynamicUrl = urlHelper.Action("PictureThumb", "Artist", new { id = imageInfo.Id, v = imageInfo.Version });

            }

            if (dynamicUrl != null) {
                return (fullUrl ? AppConfig.HostAddress + dynamicUrl : dynamicUrl);
            }

            if (!shouldExist)
                return GetUnknownImageUrl(urlHelper, imageInfo);

            return imagePersister.GetUrlAbsolute(imageInfo, size, WebHelper.IsSSL(HttpContext.Current.Request));
        }
Пример #7
0
        public ImageLoadResults FromUrl(string url, bool ignoreRestrictions, ImageSize minSize, ImageSize maxSize, bool redownload)
        {
            // if this resource already exists
              if (File.Exists(Filename))
              {
            // if we are redownloading, just delete what we have
            if (redownload)
            {
              try
              {
            File.Delete(Filename);
            File.Delete(ThumbFilename);
              }
              catch (Exception) { }
            }
            // otherwise return an "already loaded" failure
            else
            {
              return ImageLoadResults.FAILED_ALREADY_LOADED;
            }
              }

              // try to grab the image if failed, exit
              if (!Download(url)) return ImageLoadResults.FAILED;

              // verify the image file and resize it as needed
              return VerifyAndResize(minSize, maxSize);
        }
Пример #8
0
 /// <summary>
 /// Show Dialog
 /// </summary>
 /// <param name="sender">sender control</param>
 /// <param name="resolution">image size</param>
 /// <returns>filepath of photo</returns>
 public static FileInfo ShowDialog(Control sender, ImageSize resolution)
 {
     if (SystemState.CameraPresent && SystemState.CameraEnabled)
     {
         using (CameraCaptureDialog cameraCaptureDialog = new CameraCaptureDialog())
         {
             cameraCaptureDialog.Owner = sender;
             cameraCaptureDialog.Mode = CameraCaptureMode.Still;
             cameraCaptureDialog.StillQuality = CameraCaptureStillQuality.Normal;
             cameraCaptureDialog.Title = "takeIncidentPhoto".Translate();
             if (resolution != null)
             {
                 cameraCaptureDialog.Resolution = resolution.ToSize();
             }
             if (cameraCaptureDialog.ShowDialog() == DialogResult.OK)
             {
                 return new FileInfo(cameraCaptureDialog.FileName);
             }
         }
     }
     else
     {
         using(OpenFileDialog openFileDialog = new OpenFileDialog())
         {
             openFileDialog.Filter = "JPEG (*.jpg,*.jpeg)|*.jpg;*.jpeg";
             if (openFileDialog.ShowDialog() == DialogResult.OK)
             {
                 return new FileInfo(openFileDialog.FileName);
             }
         }
     }
     return null;
 }
Пример #9
0
		public void Write(IEntryImageInformation picture, ImageSize size, Image image) {

			using (var stream = new MemoryStream()) {
				image.Save(stream, GetImageFormat(picture));
				Write(picture, size, stream);
			}

		}
Пример #10
0
 public ImageInfo this[ImageSize index]
 {
     get { return _imageInfo[(int) index]; }
     private set
     {
         _imageInfo[(int) index] = value;
     }
 }
Пример #11
0
        public static MvcHtmlString PoweredByCloudCore(this System.Web.Mvc.HtmlHelper helper, ImageSize imageSize)
        {
            var urlHelper = new System.Web.Mvc.UrlHelper(helper.ViewContext.RequestContext);
            
            string imageSourceUrl = urlHelper.Asset(string.Format("poweredby/{0}.png", imageSize), "CUI");

            return new MvcHtmlString(string.Format("<a href=\"http://www.exclr8.co.za/#cloudcore\" target=\"_blank\"><img style=\"border: 0\" src=\"{0}\" /></a>", imageSourceUrl));
        }
		private void AssertDimensions(IEntryImageInformation imageInfo, ImageSize size, int width, int height) {

			using (var stream = persister.GetReadStream(imageInfo, size))
			using (var img = Image.FromStream(stream)) {
				Assert.AreEqual(width, img.Width, "Image width");
				Assert.AreEqual(height, img.Height, "Image height");
			}

		}
Пример #13
0
        public ChessBoard(Context context)
        {
            InitializeComponent();

            boardManager = new BoardManager(context);
            this.komaImageSize = context.Size;
            this.PictureSize = getImageSize();
            ClientSize = new Size(PictureSize * 8, PictureSize * 8);
            createKoma();
        }
        /// <summary>
        ///     Gets the Uri to the playlist's image at the given size
        /// </summary>
        /// <param name="playlistId">Id representing the playlist with the desired image</param>
        /// <param name="size">Size of the image desired</param>
        /// <returns>Uri to the playlist's image at the given size</returns>
        public async Task<Uri> GetPlaylistImageUri(string playlistId, ImageSize size = ImageSize.Medium)
        {
            ValidateResourceId(playlistId);

            var method = string.Format("playlists/{0}/images/default", playlistId);

            var response = await GetResourceImageUri(method, size);

            return response;
        }
Пример #15
0
        public byte[] Load(int haystackId, long photoKey, ImageSize size, int cookie)
        {
            var idx = _inMemoryIndex.Get(photoKey);

            var offset = idx[size].Offset;

            var dataSize = idx[size].Size;

            return _haystackService.Read(idx.PhotoKey, (int) size, cookie, offset, dataSize);
        }
        /// <summary>
        ///     Gets the Uri to the album's image at the given size
        /// </summary>
        /// <param name="albumId">Id representing the album with the desired image</param>
        /// <param name="size">Size of the image desired</param>
        /// <returns>Uri to the album's image at the given size</returns>
        public async Task<Uri> GetAlbumImageUri(string albumId, ImageSize size = ImageSize.Medium)
        {
            ValidateResourceId(albumId);

            var method = string.Format("albums/{0}/images/default", albumId);

            var response = await GetResourceImageUri(method, size);

            return response;
        }
        /// <summary>
        ///     Gets the Uri to the track's image at the given size
        /// </summary>
        /// <param name="trackId">Id representing the album with the desired image</param>
        /// <param name="size">Size of the image desired</param>
        /// <returns>Uri to the track's image at the given size</returns>
        public async Task<Uri> GetTrackImageUri(string trackId, ImageSize size = ImageSize.Medium)
        {
            ValidateResourceId(trackId);

            var method = string.Format("tracks/{0}/images/default", trackId);

            var response = await GetResourceImageUri(method, size);

            return response;
        }
        internal static void UpdateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId)
        {
            RemoteViews views = new RemoteViews(context.PackageName, Resource.Layout.widget);

            ImageSize minImageSize = new ImageSize(70, 70); // 70 - approximate size of ImageView in widget
            ImageLoader.Instance
                    .LoadImage(Constants.IMAGES[0], minImageSize, displayOptions, new ThisSimpleImageLoadingListener(appWidgetManager, appWidgetId, views, Resource.Id.image_left));
            ImageLoader.Instance
                    .LoadImage(Constants.IMAGES[1], minImageSize, displayOptions, new ThisSimpleImageLoadingListener(appWidgetManager, appWidgetId, views, Resource.Id.image_right));
        }
Пример #19
0
		/// <summary>
		/// Writes an image to a file, overwriting any existing file.
		/// 
		/// If the dimensions of the original image are smaller or equal than the thumbnail size,
		/// the file is simply copied. Otherwise it will be shrunk.
		/// </summary>
		/// <param name="original">Original image. Cannot be null.</param>
		/// <param name="input">Stream to be written. Cannot be null.</param>
		/// <param name="imageInfo">Image information. Cannot be null.</param>
		/// <param name="size">Image size of the saved thumbnail.</param>
		/// <param name="dimensions">Dimensions of the thumbnail.</param>
		private void GenerateThumbAndMoveImage(Image original, Stream input, IEntryImageInformation imageInfo, ImageSize size, int dimensions) {

			if (dimensions != Unlimited && (original.Width > dimensions || original.Height > dimensions)) {
				using (var thumb = ImageHelper.ResizeToFixedSize(original, dimensions, dimensions)) {
					persister.Write(imageInfo, size, thumb);
				}
			} else {
				persister.Write(imageInfo, size, input);
			}

		}
		private static string GetSuffix(ImageSize size) {
			switch (size) {
				case ImageSize.Thumb:
					return "-t";
				case ImageSize.SmallThumb:
					return "-st";
				case ImageSize.TinyThumb:
					return "-tt";
				default:
					return string.Empty;
			}
		}
		public void Write(IEntryImageInformation picture, ImageSize size, Image image) {
			
			var path = GetPath(picture, size);

			if (string.IsNullOrEmpty(path))
				return;

			EnsureDirExistsForFile(path);

			image.Save(path);					

		}
Пример #22
0
 /// <summary>
 /// returns "/img/{size}/default-{name}.{format}", "img/{size}/t{imageType}t{yearMonth}-{id}.{format}"
 /// </summary>
 /// <param name="key">
 /// t20t201410-6C294E0437664E3FA99C0CBAA4E8CCD1.png
 /// default-websitelogo.png
 /// </param>
 /// <param name="size"></param>
 /// <returns>
 /// e.g. /img/full/t20t201410-6C294E0437664E3FA99C0CBAA4E8CCD1.png
 /// e.g. /img/s80x80/t20t201410-6C294E0437664E3FA99C0CBAA4E8CCD1.png
 /// e.g. /img/s80x80/default-websitelogo.png
 /// </returns>
 public static string BuildSrc(string key, ImageSize size)
 {
     if (string.IsNullOrEmpty(key))
     {
         return "/_storage/css/404.png";
     }
     if (key.IndexOf("/", StringComparison.OrdinalIgnoreCase) == -1)
     {
         return string.Format("/img/{0}/{1}", size, key);
     }
     return key;
 }
Пример #23
0
 public static string Transform(ImageSize? size, string fileName = "")
 {
     var fName = string.IsNullOrEmpty(fileName)
         ? "http://files.0574shop.com/content/attached/2012/0314/129761890450421250.png"
         : fileName;
     /*
     return fName;
     */
     return size == null
         ? fileName
         : InsertAtEndOfFileName(fName, Enum.GetName(typeof(ImageSize), size));
 }
Пример #24
0
		public void Write(IEntryImageInformation picture, ImageSize size, Stream stream) {

			var bytes = StreamHelper.ReadStream(stream);

			var url = GetUrlAbsolute(picture, size, false);

			if (images.ContainsKey(url))
				images[url] = bytes;
			else
				images.Add(url, bytes);

		}
Пример #25
0
        /// <summary>
        /// 获取图片的高度
        /// </summary>
        /// <param name="size"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static int GetImageHeight(ImageSize size, string fileName)
        {
            var width =
                _imageFileSizeDictionary[size].Substring(_imageFileSizeDictionary[size].LastIndexOf('x') + 1).TryTo(0);

            if (!fileName.IsNotNullOrEmpty() || fileName.IndexOf('-') <= 0) return width;

            var tStr = fileName.Substring(fileName.IndexOf('-') + 1);
            tStr = tStr.Remove(tStr.IndexOf('.'));
            var originalWidth = tStr.Substring(0, tStr.IndexOf('x')).TryTo(0);
            var originalHeight = tStr.Substring(tStr.IndexOf('x') + 1).TryTo(0);
            return (int) ((width/(double) originalWidth)*originalHeight);
        }
Пример #26
0
        private Stream ScaleImageDown(string file, ImageSize imageSize)
        {
            if (String.IsNullOrEmpty(file))
                throw new ArgumentException("file is null or empty.", "file");
            if (imageSize == null)
                throw new ArgumentNullException("imageSize", "imageSize is null.");

            using (Stream imageStream = File.OpenRead(file)) {
                if (imageSize != null && imageSize != ImageSize.Original)
                    return ImageScaler.ScaleDown(imageStream, imageSize.Width, imageSize.Height, true);

                return imageStream;
            }
        }
Пример #27
0
        public static ImageDimensions GetDefaultImageDimensions(ImageSize type)
        {
            switch (type)
            {
                case ImageSize.Small:
                    return new ImageDimensions
                    {
                        Height = 200,
                        Width = 400
                    };

                default:
                    return new ImageDimensions();
            }
        }
Пример #28
0
        public static int GetImageHeight(ImageSize size, string fileName)
        {
            var r = Enum.GetName(typeof(ImageSize), size);
            var width = r.Substring(r.LastIndexOf('x') + 1).TryTo(0);
            if (fileName.IsNotNullOrEmpty() && fileName.IndexOf('-') > 0)
            {
                var tStr = fileName.Substring(fileName.IndexOf('-') + 1);
                tStr = tStr.Remove(tStr.IndexOf('.'));
                var originalWidth = tStr.Substring(0, tStr.IndexOf('x')).TryTo(0);
                var originalHeight = tStr.Substring(tStr.IndexOf('x') + 1).TryTo(0);
                return (int)((width / (double)originalWidth) * originalHeight);
            }

            return width;
        }
        public ThumbnailGenerationOptions(PointInTime pointInTime, ImageType imageType, ImageSize imageSize)
        {
            if (pointInTime == null)
                throw new ArgumentNullException("pointInTime");

            if (imageType == null)
                throw new ArgumentNullException("imageType");

            if (imageSize == null)
                throw new ArgumentNullException("imageSize");

            PointInTime = pointInTime;
            ImageType = imageType;
            ImageSize = imageSize;
        }
		private static string GetDir(ImageSize size) {

			switch (size) {
				case ImageSize.Original:
					return "Orig";
				case ImageSize.Thumb:
					return "Thumb";
				case ImageSize.SmallThumb:
					return "Small";
				case ImageSize.TinyThumb:
					return "Tiny";
				default:
					throw new NotSupportedException();
			}

		}
Пример #31
0
        private IActionResult GetImageResult(int id, ImageSize imageSize = ImageSize.Full)
        {
            var result = GetImageData(id, imageSize);

            return(result == null ? (IActionResult)NotFound(id) : File(result, "image/jpg"));
        }
Пример #32
0
 // Bitmap Profile Image
 public Bitmap GenerateProfileImageBitmap(ImageSize imageSize = ImageSize.normal)
 {
     return(_userController.GenerateProfileImageBitmap(_userDTO, imageSize));
 }
Пример #33
0
 public void DownloadProfileImageAsync(string filePath, Action <bool> successAction, Action <long, long> progressChangedAction = null, ImageSize imageSize = ImageSize.normal)
 {
     _userController.DownloadProfileImageAsync(_userDTO, filePath, successAction, progressChangedAction, imageSize);
 }
Пример #34
0
 public static string GetAvatarUrl(DiscordUserPacket packet, ImageType type = ImageType.AUTO, ImageSize size = ImageSize.x256)
 {
     if (packet.Avatar != null)
     {
         return(GetAvatarUrl(packet.Id, packet.Avatar, type, size));
     }
     return(GetAvatarUrl(ushort.Parse(packet.Discriminator)));
 }
Пример #35
0
 public Stream GetProfileImageStream(IUserDTO userDTO, ImageSize imageSize = ImageSize.normal)
 {
     return(_userQueryExecutor.GetProfileImageStream(userDTO, imageSize));
 }
Пример #36
0
 public override string GetPath(IEntryImageInformation picture, ImageSize size)
 {
     return(HttpContext.Current.Server.MapPath(string.Format("~\\EntryImg\\{0}\\{1}", picture.EntryType, GetFileName(picture, size))));
 }
Пример #37
0
 public async Task <Stream> GetProfileImageStreamAsync(ImageSize imageSize = ImageSize.normal)
 {
     return(await _taskFactory.ExecuteTaskAsync(() => GetProfileImageStream(imageSize)));
 }
Пример #38
0
        /// <summary>
        /// Resamples one VML or DrawingML image
        /// </summary>
        private static bool ResampleCore(ImageData imageData, SizeF shapeSizeInPoints, int ppi, int jpegQuality)
        {
            // The are actually several shape types that can have an image (picture, ole object, ole control), let's skip other shapes.
            if (imageData == null)
            {
                return(false);
            }

            // An image can be stored in the shape or linked from somewhere else. Let's skip images that do not store bytes in the shape.
            byte[] originalBytes = imageData.ImageBytes;
            if (originalBytes == null)
            {
                return(false);
            }

            // Ignore metafiles, they are vector drawings and we don't want to resample them.
            ImageType imageType = imageData.ImageType;

            if (imageType.Equals(ImageType.Wmf) || imageType.Equals(ImageType.Emf))
            {
                return(false);
            }

            try
            {
                double shapeWidthInches  = ConvertUtil.PointToInch(shapeSizeInPoints.Width);
                double shapeHeightInches = ConvertUtil.PointToInch(shapeSizeInPoints.Height);

                // Calculate the current PPI of the image.
                ImageSize imageSize   = imageData.ImageSize;
                double    currentPpiX = imageSize.WidthPixels / shapeWidthInches;
                double    currentPpiY = imageSize.HeightPixels / shapeHeightInches;

                Console.Write("Image PpiX:{0}, PpiY:{1}. ", (int)currentPpiX, (int)currentPpiY);

                // Let's resample only if the current PPI is higher than the requested PPI (e.g. we have extra data we can get rid of).
                if ((currentPpiX <= ppi) || (currentPpiY <= ppi))
                {
                    Console.WriteLine("Skipping.");
                    return(false);
                }

                using (Image srcImage = imageData.ToImage())
                {
                    // Create a new image of such size that it will hold only the pixels required by the desired ppi.
                    int dstWidthPixels  = (int)(shapeWidthInches * ppi);
                    int dstHeightPixels = (int)(shapeHeightInches * ppi);
                    using (Bitmap dstImage = new Bitmap(dstWidthPixels, dstHeightPixels))
                    {
                        // Drawing the source image to the new image scales it to the new size.
                        using (Graphics gr = Graphics.FromImage(dstImage))
                        {
                            gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            gr.DrawImage(srcImage, 0, 0, dstWidthPixels, dstHeightPixels);
                        }

                        // Create JPEG encoder parameters with the quality setting.
                        ImageCodecInfo    encoderInfo   = GetEncoderInfo(ImageFormat.Jpeg);
                        EncoderParameters encoderParams = new EncoderParameters();
                        encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, jpegQuality);

                        // Save the image as JPEG to a memory stream.
                        MemoryStream dstStream = new MemoryStream();
                        dstImage.Save(dstStream, encoderInfo, encoderParams);

                        // If the image saved as JPEG is smaller than the original, store it in the shape.
                        Console.WriteLine("Original size {0}, new size {1}.", originalBytes.Length, dstStream.Length);
                        if (dstStream.Length < originalBytes.Length)
                        {
                            dstStream.Position = 0;
                            imageData.SetImage(dstStream);
                            return(true);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Catch an exception, log an error and continue if cannot process one of the images for whatever reason.
                Console.WriteLine("Error processing an image, ignoring. " + e.Message);
            }

            return(false);
        }
Пример #39
0
 public Stream GetReadStream(IEntryImageInformation picture, ImageSize size)
 {
     return(new MemoryStream(images[GetUrlAbsolute(picture, size)]));
 }
Пример #40
0
 public string GetUrlAbsolute(IEntryImageInformation picture, ImageSize size)
 {
     return(picture.EntryType + "/" + picture.Id + "/" + size);
 }
Пример #41
0
        /// <summary>
        /// Resizes a set of dimensions
        /// </summary>
        /// <param name="size">The size.</param>
        /// <param name="scaleFactor">The scale factor.</param>
        /// <returns>ImageSize.</returns>
        public static ImageSize Scale(ImageSize size, double scaleFactor)
        {
            double newWidth = size.Width * scaleFactor;

            return(Resize(size.Width, size.Height, newWidth, null, null, null));
        }
Пример #42
0
        public string GenerateStaticMapURL(StaticMapRequest request)
        {
            string scheme = request.IsSSL ? "https://" : "http://";

            var parametersList = new QueryStringParametersList();

            if (!string.IsNullOrEmpty(request.ApiKey))
            {
                string apiKey = request.ApiKey;
                parametersList.Add("key", apiKey);
            }

            if (request.Center != null)
            {
                ILocationString center = request.Center;

                string centerLocation = center.LocationString;

                parametersList.Add("center", centerLocation);
            }

            if (request.Zoom != default(int))
            {
                parametersList.Add("zoom", request.Zoom.ToString());
            }

            if (request.Size.Width != default(int) || request.Size.Height != default(int))
            {
                ImageSize imageSize = request.Size;

                parametersList.Add("size", string.Format("{0}x{1}", imageSize.Width, imageSize.Height));
            }
            else
            {
                throw new ArgumentException("Size is invalid");
            }

            if (request.ImageFormat != default(ImageFormat))
            {
                string format;

                switch (request.ImageFormat)
                {
                case ImageFormat.PNG8:
                    format = "png8";
                    break;

                case ImageFormat.PNG32:
                    format = "png32";
                    break;

                case ImageFormat.GIF:
                    format = "gif";
                    break;

                case ImageFormat.JPG:
                    format = "jpg";
                    break;

                case ImageFormat.JPG_baseline:
                    format = "jpg-baseline";
                    break;

                default:
                    throw new ArgumentOutOfRangeException("ImageFormat");
                }

                parametersList.Add("format", format);
            }

            if (request.MapType != null)
            {
                string type;

                switch (request.MapType)
                {
                case MapType.Roadmap:
                    type = "roadmap";
                    break;

                case MapType.Satellite:
                    type = "satellite";
                    break;

                case MapType.Terrain:
                    type = "terrain";
                    break;

                case MapType.Hybrid:
                    type = "hybrid";
                    break;

                default:
                    throw new ArgumentOutOfRangeException("MapType");
                }

                parametersList.Add("maptype", type);
            }

            if (request.Style != null)
            {
                MapStyle style = request.Style;

                var styleComponents = new List <string>();

                if (style.MapFeature != default(MapFeature))
                {
                    string mapFeature;

                    switch (style.MapFeature)
                    {
                    case MapFeature.All:
                        mapFeature = "all";
                        break;

                    case MapFeature.Road:
                        mapFeature = "road";
                        break;

                    case MapFeature.Landscape:
                        mapFeature = "landscape";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    styleComponents.Add("feature:" + mapFeature);
                }

                if (style.MapElement != default(MapElement))
                {
                    string element;

                    switch (style.MapElement)
                    {
                    case MapElement.All:
                        element = "all";
                        break;

                    case MapElement.Geometry:
                        element = "geometry";
                        break;

                    case MapElement.Labels:
                        element = "lables";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    styleComponents.Add("element:" + element);
                }

                string hue = style.HUE;
                if (hue != null)
                {
                    styleComponents.Add("hue:" + hue);
                }

                float?lightness = style.Lightness;
                if (lightness != null)
                {
                    styleComponents.Add("lightness:" + lightness);
                }


                float?saturation = style.Saturation;
                if (saturation != null)
                {
                    styleComponents.Add("saturation:" + saturation);
                }

                float?gamma = style.Gamma;
                if (gamma != null)
                {
                    styleComponents.Add("gamma:" + gamma);
                }

                bool inverseLightness = style.InverseLightness;
                if (inverseLightness)
                {
                    styleComponents.Add("inverse_lightnes:true");
                }

                MapVisibility mapVisibility = style.MapVisibility;

                if (mapVisibility != default(MapVisibility))
                {
                    string visibility;

                    switch (mapVisibility)
                    {
                    case MapVisibility.On:
                        visibility = "on";
                        break;

                    case MapVisibility.Off:
                        visibility = "off";
                        break;

                    case MapVisibility.Simplified:
                        visibility = "simplified";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    styleComponents.Add("visibility:" + visibility);
                }

                parametersList.Add("style", string.Join("|", styleComponents));
            }

            IList <Marker> markers = request.Markers;

            if (markers != null)
            {
                foreach (Marker marker in markers)
                {
                    var markerStyleParams = new List <string>();

                    MarkerStyle markerStyle = marker.Style;
                    if (markerStyle != null)
                    {
                        if (string.IsNullOrWhiteSpace(markerStyle.Color))
                        {
                            throw new ArgumentException("Marker style color can't be empty");
                        }

                        markerStyleParams.Add("color:" + markerStyle.Color);

                        if (!string.IsNullOrWhiteSpace(markerStyle.Label))
                        {
                            markerStyleParams.Add("label:" + markerStyle.Label);
                        }

                        if (markerStyle.Size != default(MarkerSize))
                        {
                            switch (markerStyle.Size)
                            {
                            case MarkerSize.Mid:
                                markerStyleParams.Add("size:mid");
                                break;

                            case MarkerSize.Tiny:
                                markerStyleParams.Add("size:tiny");
                                break;

                            case MarkerSize.Small:
                                markerStyleParams.Add("size:small");
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        }
                    }

                    string styleString = string.Join("|", markerStyleParams);

                    string locations = string.Join("|", marker.Locations.Select(location => location.LocationString));

                    parametersList.Add("markers", string.Format("{0}|{1}", styleString, locations));
                }
            }

            IList <Path> pathes = request.Pathes;

            if (pathes != null)
            {
                foreach (Path path in pathes)
                {
                    var pathStyleParams = new List <string>();

                    PathStyle pathStyle = path.Style;

                    if (pathStyle != null)
                    {
                        if (string.IsNullOrWhiteSpace(pathStyle.Color))
                        {
                            throw new ArgumentException("Path style color can't be empty");
                        }

                        pathStyleParams.Add("color:" + pathStyle.Color);

                        if (!string.IsNullOrWhiteSpace(pathStyle.FillColor))
                        {
                            pathStyleParams.Add("fillcolor:" + pathStyle.FillColor);
                        }

                        if (pathStyle.Weight != default(int))
                        {
                            pathStyleParams.Add("weight:" + pathStyle.Weight);
                        }
                    }

                    string styleString = string.Join("|", pathStyleParams);

                    string locations = string.Join("|", path.Locations.Select(location => location.LocationString));

                    parametersList.Add("path", string.Format("{0}|{1}", styleString, locations));
                }
            }

            return(scheme + BaseUrl + "?" + parametersList.GetQueryStringPostfix());
        }
Пример #43
0
 private static string GetFileName(IEntryImageInformation picture, ImageSize size)
 {
     return(GetFileName(picture.Id, picture.Mime, GetSuffix(size)));
 }
Пример #44
0
 private static extern nn.Result GetProfileImageUrl(Profile profile,
                                                    [In, Out, MarshalAs(UnmanagedType.LPStr, SizeConst = 160)] StringBuilder outUrl, ImageSize imageSize);
Пример #45
0
 // Stream Profile IMage
 public Stream GetProfileImageStream(ImageSize imageSize = ImageSize.normal)
 {
     return(_userController.GetProfileImageStream(_userDTO, imageSize));
 }
Пример #46
0
 /// <inheritdoc />
 public Uri Build(ImageSize imageSize)
 {
     return(Build(ImageName, imageSize));
 }
Пример #47
0
 public static string GetAvatarUrl(ulong id, string hash, ImageType imageType = ImageType.AUTO, ImageSize size = ImageSize.x256)
 {
     if (imageType == ImageType.AUTO)
     {
         imageType = hash.StartsWith("a_")
             ? ImageType.GIF
             : ImageType.PNG;
     }
     return($"{CdnUrl}/avatars/{id}/{hash}.{imageType.ToString().ToLower()}?size={Math.Pow(2, 4 + (int)size)}");
 }
Пример #48
0
 /// <inheritdoc />
 public virtual Uri Build(string imageName, ImageSize imageSize)
 {
     return(UriHelper.Combine(BaseUri, imageName));
 }
Пример #49
0
        // Stream Profile Image
        public Stream GetProfileImageStream(IUserDTO userDTO, ImageSize imageSize = ImageSize.normal)
        {
            var url = _userQueryGenerator.DownloadProfileImageURL(userDTO, imageSize);

            return(_webHelper.GetResponseStream(url));
        }
 // Returns the image
 public FileStreamResult GetImage(string path, string id, bool allowCompress, ImageSize size, params FileManagerDirectoryContent[] data)
 {
     return(new FileStreamResult((new MemoryStream(new WebClient().DownloadData(this.FilesPath + path))), "APPLICATION/octet-stream"));
 }
Пример #51
0
 protected void SetImageSize(ImageSize size)
 {
     RunCommand(Command.WRITE_DATA, new byte[] { 0x04, 0x01, 0x00, 0x19, (byte)size }, 5);
     Reset();
 }
Пример #52
0
        public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation?orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("outputPath");
            }

            var skiaOutputFormat = GetImageFormat(selectedOutputFormat);

            var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
            var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
            var blur         = options.Blur ?? 0;
            var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);

            using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
            {
                if (bitmap == null)
                {
                    throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
                }

                //_logger.Info("Color type {0}", bitmap.Info.ColorType);

                var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);

                if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
                {
                    // Just spit out the original file if all the options are default
                    return(inputPath);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var width  = Convert.ToInt32(Math.Round(newImageSize.Width));
                var height = Convert.ToInt32(Math.Round(newImageSize.Height));

                using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
                {
                    // scale image
                    var resizeMethod = SKBitmapResizeMethod.Lanczos3;

                    bitmap.Resize(resizedBitmap, resizeMethod);

                    // If all we're doing is resizing then we can stop now
                    if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
                    {
                        _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
                        using (var outputStream = new SKFileWStream(outputPath))
                        {
                            resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            return(outputPath);
                        }
                    }

                    // create bitmap to use for canvas drawing used to draw into bitmap
                    using (var saveBitmap = new SKBitmap(width, height)) //, bitmap.ColorType, bitmap.AlphaType))
                        using (var canvas = new SKCanvas(saveBitmap))
                        {
                            // set background color if present
                            if (hasBackgroundColor)
                            {
                                canvas.Clear(SKColor.Parse(options.BackgroundColor));
                            }

                            // Add blur if option is present
                            if (blur > 0)
                            {
                                // create image from resized bitmap to apply blur
                                using (var paint = new SKPaint())
                                    using (var filter = SKImageFilter.CreateBlur(blur, blur))
                                    {
                                        paint.ImageFilter = filter;
                                        canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
                                    }
                            }
                            else
                            {
                                // draw resized bitmap onto canvas
                                canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
                            }

                            // If foreground layer present then draw
                            if (hasForegroundColor)
                            {
                                Double opacity;
                                if (!Double.TryParse(options.ForegroundLayer, out opacity))
                                {
                                    opacity = .4;
                                }

                                canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
                            }

                            if (hasIndicator)
                            {
                                DrawIndicator(canvas, width, height, options);
                            }

                            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
                            using (var outputStream = new SKFileWStream(outputPath))
                            {
                                saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            }
                        }
                }
            }
            return(outputPath);
        }
Пример #53
0
 // Download Profile Image
 public bool DownloadProfileImage(string filePath, ImageSize imageSize = ImageSize.normal)
 {
     return(_userController.DownloadProfileImage(_userDTO, filePath, imageSize));
 }
Пример #54
0
        public void SaveImageSize(string path, DateTime imageDateModified, ImageSize size)
        {
            var cacheHash = GetImageSizeKey(path, imageDateModified);

            SaveImageSize(size, cacheHash, true);
        }
 public SizeSpecificImageTargetSizeNotEqualToActualSizeError(ImageSize actualSize)
 {
     ActualSize = actualSize;
 }
        public ImageSize GetEnhancedImageSize(IHasImages item, ImageType imageType, int imageIndex, ImageSize originalImageSize)
        {
            var items = GetItemsWithImages(item);

            if (items.Count == 0)
            {
                return(originalImageSize);
            }

            if (imageType == ImageType.Thumb)
            {
                return(new ImageSize
                {
                    Height = ThumbImageHeight,
                    Width = ThumbImageWidth
                });
            }

            return(new ImageSize
            {
                Height = SquareImageSize,
                Width = SquareImageSize
            });
        }
Пример #57
0
 public bool HasImage(IEntryImageInformation picture, ImageSize size)
 {
     return(images.ContainsKey(GetUrlAbsolute(picture, size)));
 }
Пример #58
0
 public ImageId Cover(ImageSize size)
 {
     return(new ImageId(NativeMethods.sp_album_cover(this._handle, size)));
 }
Пример #59
0
        IFacebookAccount populateAccount(global::Facebook.CoreKit.AccessToken accessToken, global::Facebook.CoreKit.Profile profile, ImageSize photoSize = null)
        {
            if (accessToken == null)
            {
                return(null);
            }

            DateTime?expires = null;

            if (accessToken.ExpirationDate != null)
            {
                expires = (DateTime)accessToken.ExpirationDate;
            }
            DateTime?refreshed = null;

            if (accessToken.RefreshDate != null)
            {
                refreshed = (DateTime)accessToken.RefreshDate;
            }

            var permissions = new List <string>();

            if (accessToken.Permissions != null)
            {
                foreach (var p in accessToken.Permissions.ToArray <NSString>())
                {
                    permissions.Add(p.ToString());
                }
            }

            var declinedPermissions = new List <string>();

            if (accessToken.DeclinedPermissions != null)
            {
                foreach (var p in accessToken.DeclinedPermissions.ToArray <NSString>())
                {
                    declinedPermissions.Add(p.ToString());
                }
            }

            Uri photoUri = null;

            if (profile != null)
            {
                if (photoSize == null)
                {
                    photoSize = new ImageSize();
                }
                var u = profile.ImageUrl(
                    photoSize.IsSquare ? global::Facebook.CoreKit.ProfilePictureMode.Square : global::Facebook.CoreKit.ProfilePictureMode.Normal,
                    new CoreGraphics.CGSize(photoSize.Width, photoSize.Height));
                if (u != null)
                {
                    photoUri = new Uri(u.AbsoluteString, UriKind.Absolute);
                }
            }

            Uri linkUri = null;

            if (profile?.LinkUrl != null && !string.IsNullOrWhiteSpace(profile.LinkUrl.AbsoluteString))
            {
                linkUri = new Uri(profile.LinkUrl.AbsoluteString, UriKind.Absolute);
            }

            return(new FacebookAccount
            {
                Id = profile?.UserId ?? accessToken.UserId,
                ApplicationId = accessToken.AppId,
                UserId = profile?.UserId ?? accessToken.UserId,
                AccessToken = accessToken.TokenString,
                AccessTokenExpires = expires,
                Permissions = permissions,
                DeclinedPermissions = declinedPermissions,
                Name = profile?.Name,
                FirstName = profile?.FirstName,
                LastName = profile?.LastName,
                MiddleName = profile?.MiddleName,
                PhotoUri = photoUri,
                LinkUri = linkUri
            });
        }
Пример #60
0
 public nn.Result GetProfileImageUrl(ref string outUrl, ImageSize imageSize)
 {
     return(new nn.Result());
 }