/// <summary> /// Resizes with ScaleToFit of crop is true /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="crop">if set to true ScaleToFill is used, if not ScaleToFit</param> /// <param name="encoding"></param> /// <returns></returns> public byte[] Resize(int width, int height, bool crop, ImageEncoding encoding) { if (width < 0) throw new ArgumentException("width < 0"); if (height < 0) throw new ArgumentException("height < 0"); BitmapSource bitmapSource = null; if (width > 0 && height > 0 && crop) { bitmapSource = ScaleToFill(width, height); } else if (width > 0 && height > 0 && !crop) { bitmapSource = ScaleToFit(width, height); } else if (width > 0) { bitmapSource = ResizeImageByWidth(_imageBytes, width); } _imageBytes = EncodeImageData(bitmapSource, encoding); return _imageBytes; }
/// <summary> /// Initializes a new instance of the <see cref="Image"/> class from a single image response. /// </summary> /// <param name="response">The response.</param> internal Image(ExternalInterface.CaptureSingleImageResponse response) { ImageId = response.ImageId; Data = response.Data.ToByteArray(); Encoding = MapImageEncoding(response.ImageEncoding); FrameTimestamp = response.FrameTimeStamp; }
protected override void ProcessRecord() { if (parPath.StartsWith(@".\")) { parPath = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parPath.Substring(2)); } parPath = System.IO.Path.GetFullPath(parPath); string htmlData = File.ReadAllText(parPath); htmlData = Regex.Replace(htmlData, "(?=<img)(.*?)src=[\"|'](.*?)[\"|']", delegate(Match match) { Image rawImage = ((new Uri(match.Groups[2].Value).IsFile)) ? rawImage = ImageEncoding.ReadImage(System.IO.Path.GetFullPath(match.Groups[2].Value)) : ImageEncoding.DownloadImage(match.Groups[2].Value); string encodedImage = ImageEncoding.ImageToBase64String(rawImage); return(string.Format("{0}src=\"data:image/image;base64,{1}\"", match.Groups[1].Value, encodedImage)); }); string newName = string.Format("{1}\\{0}.htapp", System.IO.Path.GetFileNameWithoutExtension(parPath), System.IO.Path.GetDirectoryName(parPath)); string header = Templates.StandardBlock; header = header.Replace("$WIDTH$", parWidth.ToString()); header = header.Replace("$HEIGHT$", parHeight.ToString()); header = header.Replace("$TITLE$", parTitle); htmlData = header + htmlData; File.WriteAllText(newName, htmlData); }
/// <summary> /// Выполняет кодирование указанного изображения в целевой формат и возвращает результат в виде массива байтов /// </summary> /// <param name="image">Кодируемое изображение</param> /// <param name="encoding">Значение перечисления <see cref="ImageEncoding"/>, определяющее целевой формат</param> /// <param name="parameters">Необязательные параметры кодирования</param> /// <returns>Массив <see cref="byte"/>, представляющий кодированное изображение</returns> public static byte[] Imencode(IInputArray image, ImageEncoding encoding = ImageEncoding.Jpeg, params int[] parameters) { byte[] result = null; string destEncoding = GetEncoding(ref encoding); using (VectorOfByte buffer = new VectorOfByte()) { Imencode(destEncoding, image, buffer, parameters); result = buffer.ToArray(); } return(result); }
/// <summary> /// Выполняет кодирование указанного изображения в целевой формат и возвращает результат в виде массива байтов /// </summary> /// <param name="image">Кодируемое изображение</param> /// <param name="encoding">Значение перечисления <see cref="ImageEncoding"/>, определяющее целевой формат</param> /// <param name="parameters">Необязательные параметры кодирования</param> /// <returns>Массив <see cref="byte"/>, представляющий кодированное изображение</returns> public static byte[] Imencode(IInputArray image, ImageEncoding encoding = ImageEncoding.Jpeg, params int[] parameters) { byte[] result = null; string destEncoding = GetEncoding(ref encoding); using (VectorOfByte buffer = new VectorOfByte()) { Imencode(destEncoding, image, buffer, parameters); result = buffer.ToArray(); } return result; }
private static string GetEncoding(ref ImageEncoding destEncoding) { string result = null; switch (destEncoding) { case ImageEncoding.Default: case ImageEncoding.Jpeg: result = ".jpg"; break; case ImageEncoding.Bmp: result = ".bmp"; break; default: throw new ArgumentOutOfRangeException("destEncoding"); } return result; }
/// <summary> /// Gets the encoding file extension. /// </summary> /// <param name="encoding"> /// The image encoding format. /// </param> /// <returns> /// The file extension associated with the specified encoding. /// </returns> public static String GetEncodingFileExtension(ImageEncoding encoding) { String ext = String.Empty; switch (encoding) { case ImageEncoding.Bitmap: ext = "bmp"; break; case ImageEncoding.GIF: ext = "gif"; break; case ImageEncoding.JPEG: ext = "jpg"; break; case ImageEncoding.PNG: ext = "png"; break; } return ext; }
private static string GetEncoding(ref ImageEncoding destEncoding) { string result = null; switch (destEncoding) { case ImageEncoding.Default: case ImageEncoding.Jpeg: result = ".jpg"; break; case ImageEncoding.Bmp: result = ".bmp"; break; default: throw new ArgumentOutOfRangeException("destEncoding"); } return(result); }
private static MagickImage Decode(AwesomeReader ar, ImageEncoding encoding, uint bpp, uint mipmap, uint width, uint height, uint bpl, bool ps2Texture = false) { // Image starts at bottom left corner switch (encoding) { case ImageEncoding.BMP: return(DecodeBMP(ar, bpp, width, height, bpl)); case ImageEncoding.DXT1: return(bpp == 8 ? DecodeBMP(ar, bpp, width, height, bpl, false) : DecodeDXT(ar, bpp, width, height, encoding)); case ImageEncoding.DXT5: case ImageEncoding.ATI2: return(DecodeDXT(ar, bpp, width, height, encoding)); } return(null); }
/// <summary> /// Gets the encoding file extension. /// </summary> /// <param name="encoding"> /// The image encoding format. /// </param> /// <returns> /// The file extension associated with the specified encoding. /// </returns> public static String GetEncodingFileExtension(ImageEncoding encoding) { String ext = String.Empty; switch (encoding) { case ImageEncoding.Bitmap: ext = "bmp"; break; case ImageEncoding.GIF: ext = "gif"; break; case ImageEncoding.JPEG: ext = "jpg"; break; case ImageEncoding.PNG: ext = "png"; break; } return(ext); }
/// <summary> /// Save this image to png/jpeg/WebP stream of bytes /// </summary> /// <param name="encoding">The output image type</param> /// <param name="quality">png: 0, jpeg/WebP: 10 - 100</param> public static bool TrySave(this SciterImage sciterImage, out byte[] buffer, ImageEncoding encoding, uint quality = 0) { buffer = null; return(sciterImage?.TrySaveInternal(buffer: out buffer, encoding: encoding, quality: quality) == true); }
private static MagickImage DecodeDXT(AwesomeReader ar, uint bpp, uint width, uint height, ImageEncoding encoding, bool x360 = true) { uint imageSize; string compression; switch (encoding) { default: case ImageEncoding.DXT1: imageSize = (width * height) / 2; // 4bpp compression = "DXT1"; break; case ImageEncoding.DXT5: imageSize = width * height; // 8bpp compression = "DXT5"; break; case ImageEncoding.ATI2: imageSize = width * height; // 8bpp compression = "ATI2"; break; } if (encoding == ImageEncoding.DXT1) { const int PIXELS_PER_BLOCK = 16; int blockSize = (PIXELS_PER_BLOCK * (int)bpp) / 8; byte[] data = ar.ReadBytes((int)imageSize); if (x360) { SwapBytes(data); } Color FromRGB565(int c) => Color.FromArgb( 0xFF, (c & 0b1111_1000_0000_0000) >> 8, (c & 0b0000_0111_1110_0000) >> 3, (c & 0b0000_0000_0001_1111) << 3); Color MultiplyColor(Color c, float mult) => Color.FromArgb( (int)(c.A * mult), (int)(c.R * mult), (int)(c.G * mult), (int)(c.B * mult)); Color AddColors(Color a, Color b) => Color.FromArgb( a.A + b.A, a.R + b.R, a.G + b.G, a.B + b.B); int idx = 0; var colors = new Color[4]; var pixels = new Color[16]; int w, h; var imageBytes = new byte[width * height * 4]; // 32-bit color for (int y = 0; y < (height >> 2); y++) { for (int x = 0; x < (width >> 2); x++) { // Colors - 4 bytes colors[0] = FromRGB565(data[idx] | data[idx + 1] << 8); colors[1] = FromRGB565(data[idx + 2] | data[idx + 3] << 8); colors[2] = AddColors(MultiplyColor(colors[0], 0.66f), MultiplyColor(colors[1], 0.33f)); colors[3] = AddColors(MultiplyColor(colors[0], 0.33f), MultiplyColor(colors[1], 0.66f)); //colors[2] = AddColors(MultiplyColor(colors[0], 0.5f), MultiplyColor(colors[1], 0.5f)); //colors[3] = Color.FromArgb(0); // Indices - 4 bytes (16 pixels) pixels[0] = colors[(data[idx + 4] & 0b00_00_00_11)]; // Row 1
/// <summary> /// Выполняет кодирование указанного изображения в целевой формат /// </summary> /// <param name="image">Кодируемое изображение</param> /// <param name="buffer">Буфер, в который выполняется сохранение</param> /// <param name="encoding">Значение перечисления <see cref="ImageEncoding"/>, определяющее целевой формат</param> /// <param name="parameters">Необязательные параметры кодирования</param> public static void Imencode(IInputArray image, VectorOfByte buffer, ImageEncoding encoding = ImageEncoding.Jpeg, params int[] parameters) { string destEncoding = GetEncoding(ref encoding); Imencode(destEncoding, image, buffer, parameters); }
public byte[] ResizeIfWidthLargerThan(int width, ImageEncoding encoding) { return(Resize(width, 0, encoding)); }
public string UploadPhoto(Image image, ImageEncoding encoding, Size imageTargetSize, string filePathAndName) { return(base.ExecuteFunction("UploadPhoto", delegate() { filePathAndName = filePathAndName.Replace(" ", "%20"); //TODO:COULD: Sanitize this a littler better Image resizedImage = ImageFormatter.Resize(image, ResizeMode.Fill, (AnchorStyles.Middle | AnchorStyles.Center), imageTargetSize.Width, imageTargetSize.Height); using (AmazonS3Client client = new AmazonS3Client(this.AmazonKeyID, this.AmazonSecret, RegionEndpoint.USEast1)) { PutObjectResponse result = null; ImageCodecInfo codecInfo = null; EncoderParameters encoderParameters = null; switch (encoding) { case ImageEncoding.PNG: codecInfo = GetCodecInfo("image/png"); encoderParameters = new EncoderParameters(0); if (!filePathAndName.ToLower().EndsWith("png")) { filePathAndName += ".png"; } break; case ImageEncoding.JPEG: default: encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L); codecInfo = GetCodecInfo("image/jpeg"); if (!filePathAndName.ToLower().EndsWith("jpg")) { filePathAndName += ".jpg"; } break; } using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { resizedImage.Save(memoryStream, codecInfo, encoderParameters); memoryStream.Position = 0; PutObjectRequest request = new PutObjectRequest() { BucketName = this.AmazonBucket, Key = filePathAndName, CannedACL = S3CannedACL.PublicRead, InputStream = memoryStream }; result = client.PutObject(request); } if (result == null || (result.HttpStatusCode != HttpStatusCode.OK && result.HttpStatusCode != HttpStatusCode.Created)) { throw new UIException("Error saving file to cloud storage. Please try again in a few moments."); } else { return AmazonUtility.ConstructAmazonUrl(this.AmazonCloudFrontUrl, this.AmazonPublicUrl, this.AmazonBucket, filePathAndName); } } })); }
public byte[] Resize(int width, ImageEncoding encoding) { return Resize(width, 0, encoding); }
/// <summary> /// Resizes with ScaleToFill /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="encoding"></param> /// <returns></returns> public byte[] Resize(int width, int height, ImageEncoding encoding) { return Resize(width, height, true, encoding); }
private byte[] EncodeImageData(ImageSource image, ImageEncoding encoding) { byte[] buffer = null; BitmapEncoder encoder = null; switch (encoding) { case ImageEncoding.Jpg100: encoder = new JpegBitmapEncoder { QualityLevel = 100 }; break; case ImageEncoding.Jpg95: encoder = new JpegBitmapEncoder { QualityLevel = 95 }; break; case ImageEncoding.Jpg90: encoder = new JpegBitmapEncoder { QualityLevel = 90 }; break; case ImageEncoding.Jpg: encoder = new JpegBitmapEncoder(); break; case ImageEncoding.Bmp: encoder = new BmpBitmapEncoder(); break; case ImageEncoding.Png: encoder = new PngBitmapEncoder(); break; case ImageEncoding.Tiff: encoder = new TiffBitmapEncoder(); break; case ImageEncoding.Gif: encoder = new GifBitmapEncoder(); break; case ImageEncoding.Wmp: encoder = new WmpBitmapEncoder(); break; } if (image is BitmapSource) { var stream = new MemoryStream(); if (encoder != null) { var bitmapFrame = BitmapFrame.Create(image as BitmapSource); encoder.Frames.Add(bitmapFrame); encoder.Save(stream); } stream.Seek(0L, SeekOrigin.Begin); buffer = new byte[stream.Length]; var reader = new BinaryReader(stream); reader.Read(buffer, 0, (int)stream.Length); reader.Close(); stream.Close(); } return buffer; }
public void Render(TextWriter sw) { sw.WriteLine(@" <style> #container { position:relative; } img { width: 336px; height: 414px; } th{ font-size: 40 } .highlight { position:absolute; width: 56px; height:52px; border: 2px solid red; } .crop0-left{ left:0px; } .crop1-left{ left:56px; } .crop2-left{ left:112px; } .crop3-left{ left:168px; } .crop4-left{ left:224px; } .crop5-left{ left:280px; } .crop0-top{ top:0px; } .crop1-top{ top:52px; } .crop2-top{ top:103px; } .crop3-top{ top:155px; } .crop4-top{ top:207px; } .crop5-top{ top:259px; } .crop6-top{ top:310px; } .crop7-top{ top:362px; }"); // td:first-child{ // border:5px solid lime; //} sw.WriteLine("</style>"); sw.WriteLine("<table>"); var names = ImageEncoding.ToDictionary(x => x.Value, x => x.Key); var patches = PatchEncoding.ToDictionary(x => x.Value, x => x.Key); foreach (var row in Rows.Take(3000)) { sw.WriteLine(row.ToString(names, patches)); } sw.WriteLine("</table>"); }
// called when a user uploads images recieving the listing id public ActionResult Upload(int id) { int listingId = id; CoreysListEntities db = new CoreysListEntities(); // for each of the requested files for (int i = 0; i < Request.Files.Count; i++) { try { // create a new [image] CoreysList.Entity.Image newImage = new CoreysList.Entity.Image(); // Uploaded file HttpPostedFileBase file = Request.Files[i]; // Get the size of the file newImage.ImageSize = file.ContentLength; // get the file name newImage.FileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1); // get the type of file .jpg .gif .png etc.. newImage.ImageType = file.ContentType; // create a new byte array to fit the content size byte[] imageData = new byte[file.ContentLength]; // read in the file withe the byte array and content size file.InputStream.Read(imageData, 0, (int)file.ContentLength); // reposition the input stream to the beginning file.InputStream.Position = 0; // stream the file again into a System.Drawing.Image System.Drawing.Image sysImg = System.Drawing.Image.FromStream(file.InputStream); // assign the sizes from system image to coreyslist image newImage.ImageHeight = sysImg.Height; newImage.ImageWidth = sysImg.Width; newImage.ImageContent = imageData; // create encoding object to send image type ImageEncoding imgResizerEnc = new ImageEncoding(); // set the values for thumb images int thumbHeight = 75; int thumbWidth = 75; // switch statement to get the content type switch (file.ContentType) { case "image/jpeg": imgResizerEnc = ImageEncoding.Jpg90; break; case "image/gif": imgResizerEnc = ImageEncoding.Gif; break; case "image/png": imgResizerEnc = ImageEncoding.Png; break; } // create a resizer and send the image content ImageResizer resizer = new ImageResizer(imageData); // call the resizer method along with the desired height, width and img type byte[] thumbData = resizer.Resize(thumbHeight, thumbWidth, imgResizerEnc); // save the new thumb data for the coreyslist image entity newImage.ThumbContent = thumbData; newImage.ThumbSize = thumbData.Length; newImage.ThumbWidth = thumbWidth; newImage.ThumbHeight = thumbHeight; // connect image to the correct listing through listing ID newImage.ListingID = listingId; newImage.CreatedDate = DateTime.Now; newImage.CreatedBy = System.Web.HttpContext.Current.Session["UserId"].ToString(); // To save file, use SaveAs method db.Images.Add(newImage); db.SaveChanges(); } catch (Exception e) { throw e; } } // Return partial view EditListingImagesViewModel editListingImagesViewModel = new EditListingImagesViewModel(listingId); return(PartialView("~/views/Accounts/_EditListingImages.cshtml", editListingImagesViewModel)); }
/// <summary> /// Save this image to png/jpeg/WebP stream of bytes /// </summary> /// <param name="encoding">The output image type</param> /// <param name="quality">png: 0, jpeg/WebP: 10 - 100</param> public static byte[] Save(this SciterImage sciterImage, ImageEncoding encoding, uint quality = 0) { return(sciterImage?.SaveInternal(encoding: encoding, quality: quality)); }
// called when a user uploads images recieving the listing id public ActionResult Upload(int id) { int listingId = id; CoreysListEntities db = new CoreysListEntities(); // for each of the requested files for (int i = 0; i < Request.Files.Count; i++) { try { // create a new [image] CoreysList.Entity.Image newImage = new CoreysList.Entity.Image(); // Uploaded file HttpPostedFileBase file = Request.Files[i]; // Get the size of the file newImage.ImageSize = file.ContentLength; // get the file name newImage.FileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1); // get the type of file .jpg .gif .png etc.. newImage.ImageType = file.ContentType; // create a new byte array to fit the content size byte[] imageData = new byte[file.ContentLength]; // read in the file withe the byte array and content size file.InputStream.Read(imageData, 0, (int)file.ContentLength); // reposition the input stream to the beginning file.InputStream.Position = 0; // stream the file again into a System.Drawing.Image System.Drawing.Image sysImg = System.Drawing.Image.FromStream(file.InputStream); // assign the sizes from system image to coreyslist image newImage.ImageHeight = sysImg.Height; newImage.ImageWidth = sysImg.Width; newImage.ImageContent = imageData; // create encoding object to send image type ImageEncoding imgResizerEnc = new ImageEncoding(); // set the values for thumb images int thumbHeight = 75; int thumbWidth = 75; // switch statement to get the content type switch (file.ContentType) { case "image/jpeg": imgResizerEnc = ImageEncoding.Jpg90; break; case "image/gif": imgResizerEnc = ImageEncoding.Gif; break; case "image/png": imgResizerEnc = ImageEncoding.Png; break; } // create a resizer and send the image content ImageResizer resizer = new ImageResizer(imageData); // call the resizer method along with the desired height, width and img type byte[] thumbData = resizer.Resize(thumbHeight, thumbWidth, imgResizerEnc); // save the new thumb data for the coreyslist image entity newImage.ThumbContent = thumbData; newImage.ThumbSize = thumbData.Length; newImage.ThumbWidth = thumbWidth; newImage.ThumbHeight = thumbHeight; // connect image to the correct listing through listing ID newImage.ListingID = listingId; newImage.CreatedDate = DateTime.Now; newImage.CreatedBy = System.Web.HttpContext.Current.Session["UserId"].ToString(); // To save file, use SaveAs method db.Images.Add(newImage); db.SaveChanges(); } catch (Exception e) { throw e; } } // Return partial view EditListingImagesViewModel editListingImagesViewModel = new EditListingImagesViewModel(listingId); return PartialView("~/views/Accounts/_EditListingImages.cshtml", editListingImagesViewModel); }
public byte[] ResizeIfWidthLargerThan(int width, ImageEncoding encoding) { return Resize(width, 0, encoding); }