public static async Task <BitmapImage> LoadWebPImageAsync(string url) { try { if (string.IsNullOrEmpty(url)) { return(null); } System.Net.WebClient wc = new System.Net.WebClient(); wc.Headers.Add("Referer", "https://hitomi.la/"); Byte[] MyData = await wc.DownloadDataTaskAsync(url); wc.Dispose(); WebP webP = new WebP(); Bitmap bitmap = webP.Decode(MyData); MemoryStream ms = new MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); var bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = ms; bi.CacheOption = BitmapCacheOption.OnLoad; bi.EndInit(); return(bi); } catch { return(null); } }
public static Bitmap fromWebP(string filepath) { using (WebP webp = new WebP()) { return(webp.Load(filepath)); } }
/// <summary>resize the png image</summary> /// <param name="sourceUrl">valid source image url</param> /// <param name="destPath">destination image path that saved image there</param> /// <param name="width">width that image resized to them</param> /// <param name="height">height that image resized to them</param> /// <param name="compress">compress image if that true</param> /// <returns>return true if do correctly else return false</returns> public static bool ResizePngForWeb(string sourceUrl, string destPath, int width, int height, bool compress = false) { try { if (String.IsNullOrEmpty(sourceUrl) || String.IsNullOrEmpty(destPath) || width <= 0 || height <= 0) { return(false); } using (WebP webp = new WebP()) { Bitmap bmp = new Bitmap(Helper.DownloadImage(sourceUrl)); var webp_byte = webp.EncodeLossless(bmp); if (compress) { bmp = webp.GetThumbnailFast(webp_byte, width, height); } else { bmp = webp.GetThumbnailQuality(webp_byte, width, height); } bmp.Save(destPath, System.Drawing.Imaging.ImageFormat.Png); } return(true); } catch { throw; } }
public static void toWebP(Bitmap bmp, string outputpath, int quality) { using (WebP webp = new WebP()) { webp.Save(bmp, outputpath, quality); } }
/// <summary> /// Test for load from file function /// </summary> private void ButtonLoad_Click(object sender, System.EventArgs e) { try { using (OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog()) { openFileDialog.Filter = "Image files (*.webp, *.png, *.tif, *.tiff)|*.webp;*.png;*.tif;*.tiff"; openFileDialog.FileName = ""; if (openFileDialog.ShowDialog() == DialogResult.OK) { this.buttonSave.Enabled = true; this.buttonSave.Enabled = true; string pathFileName = openFileDialog.FileName; if (Path.GetExtension(pathFileName) == ".webp") { using (WebP webp = new WebP()) this.pictureBox.Image = webp.Load(pathFileName); } else { this.pictureBox.Image = Image.FromFile(pathFileName); } } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonLoad_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static Bitmap getThumbnail(string path, int width = 64, int height = 64) { switch (Path.GetExtension(path).ToLower()) { case ".tga": TGA tga = new TGA(path); Bitmap rawThumbnail = tga.GetThumbnail(); Bitmap thumbnail = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(thumbnail)) { g.DrawImage(rawThumbnail, 0, 0, width, height); return(thumbnail); } case ".webp": using (WebP webp = new WebP()) { return(webp.LoadThumbnail(path, width, height)); } case ".emf": using (Metafile source = new Metafile(path)) { Bitmap target = new Bitmap(width, height); using (var g = Graphics.FromImage(target)) { g.Clear(Color.White); g.DrawImage(source, 0, 0, width, height); return(target); } } default: Image src = Image.FromFile(path); return((Bitmap)src.GetThumbnailImage(width, height, () => false, IntPtr.Zero)); } }
private void GetImageFromStream(Stream stream, Enums.ImageType imageType, SourceList <BitmapSource> imageList, CancellationToken token) { using var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); token.ThrowIfCancellationRequested(); // start of expensive operation Bitmap bitmap; switch (imageType) { case Enums.ImageType.Default: bitmap = new Bitmap(memoryStream); break; case Enums.ImageType.WebP: byte[] b = memoryStream.ToArray(); using (WebP webp = new WebP()) bitmap = webp.Decode(b); break; default: throw new BadImageFormatException(); } var bitmapSource = ConvertStreamToSource(bitmap); bitmapSource.Freeze(); token.ThrowIfCancellationRequested(); // end imageList.Add(bitmapSource); bitmap.Dispose(); }
/// <summary>resize the webp image</summary> /// <param name="sourcePath">valid source image path</param> /// <param name="destPath">destination image path that saved image there</param> /// <param name="width">width that image resized to them</param> /// <param name="height">height that image resized to them</param> /// <param name="compress">compress image if that true</param> /// <returns>return true if do correctly else return false</returns> public static bool ResizeWebP(string sourcePath, string destPath, int width, int height, bool compress = false) { try { if (String.IsNullOrEmpty(sourcePath) || String.IsNullOrEmpty(destPath) || width <= 0 || height <= 0) { return(false); } using (WebP webp = new WebP()) { var webp_byte = webp.LoadByte(sourcePath); Bitmap bmp; if (compress) { bmp = webp.GetThumbnailFast(webp_byte, width, height); } else { bmp = webp.GetThumbnailQuality(webp_byte, width, height); } webp.Save(bmp, destPath); } return(true); } catch { throw; } }
/// <summary> /// Test for advanced decode function /// </summary> private void ButtonCropFlip_Click(object sender, EventArgs e) { try { using (OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog()) { openFileDialog.Filter = "WebP files (*.webp)|*.webp"; openFileDialog.FileName = ""; if (openFileDialog.ShowDialog() == DialogResult.OK) { string pathFileName = openFileDialog.FileName; byte[] rawWebP = File.ReadAllBytes(pathFileName); WebPDecoderOptions decoderOptions = new WebPDecoderOptions(); decoderOptions.use_cropping = 1; decoderOptions.crop_top = 100; //Top beging of crop area decoderOptions.crop_left = 100; //Left beging of crop area decoderOptions.crop_height = 400; //Height of crop area decoderOptions.crop_width = 400; //Width of crop area decoderOptions.use_threads = 1; //Use multhreading decoderOptions.flip = 1; //Flip the image using (WebP webp = new WebP()) this.pictureBox.Image = webp.Decode(rawWebP, decoderOptions); } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonCrop_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Test GetInfo function /// </summary> private void ButtonInfo_Click(object sender, EventArgs e) { int width; int height; bool has_alpha; bool has_animation; string format; try { using (OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog()) { openFileDialog.Filter = "WebP images (*.webp)|*.webp"; openFileDialog.FileName = ""; if (openFileDialog.ShowDialog() == DialogResult.OK) { string pathFileName = openFileDialog.FileName; byte[] rawWebp = File.ReadAllBytes(pathFileName); using (WebP webp = new WebP()) webp.GetInfo(rawWebp, out width, out height, out has_alpha, out has_animation, out format); MessageBox.Show("Width: " + width + "\n" + "Height: " + height + "\n" + "Has alpha: " + has_alpha + "\n" + "Is animation: " + has_animation + "\n" + "Format: " + format, "Information"); } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonInfo_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary>convert webp image to png and resize image</summary> /// <param name="sourceUrl">valid source image url</param> /// <param name="destPath">destination image path that saved image there</param> /// <param name="width">width that image resized to them</param> /// <param name="height">height that image resized to them</param> /// <param name="compress">compress image if that true</param> /// <returns>return true if do correctly else return false</returns> public static bool WebPToPngFromWeb(string sourceUrl, string destPath, int width, int height, bool compress = false) { try { if (String.IsNullOrEmpty(sourceUrl) || String.IsNullOrEmpty(destPath) || width <= 0 || height <= 0) { return(false); } using (WebP webp = new WebP()) { var stream = Helper.DownloadImage(sourceUrl); var webp_byte = Helper.ReadByte(stream); Bitmap bmp; if (compress) { bmp = webp.GetThumbnailFast(webp_byte, width, height); } else { bmp = webp.GetThumbnailQuality(webp_byte, width, height); } bmp.Save(destPath, System.Drawing.Imaging.ImageFormat.Png); } return(true); } catch { throw; } }
private void ouvrirToolStripMenuItem_Click(object sender, EventArgs e) { if (ofdFile.ShowDialog() == DialogResult.OK) { Console.WriteLine(ofdFile.FileName); Console.WriteLine(Path.GetExtension(ofdFile.FileName)); Bitmap img; if (Path.GetExtension(ofdFile.FileName) == ".webp") { WebP webp = new WebP(); img = webp.Load(ofdFile.FileName); } else { img = new Bitmap(ofdFile.FileName); } pibImg.Image = img; lsbMetadata.Items.Clear(); IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(ofdFile.FileName); foreach (var dir in directories) { foreach (var item in dir.Tags) { Console.WriteLine(item); lsbMetadata.Items.Add(item); } } } }
/// <summary>convert webp image to png</summary> /// <param name="sourceUrl">valid source image path</param> /// <param name="destPath">destination image path that saved image there</param> /// <param name="compress">compress image if that true</param> /// <returns>return true if do correctly else return false</returns> public static bool WebPToPng(string sourcePath, string destPath, bool compress = false) { try { if (String.IsNullOrEmpty(sourcePath) || String.IsNullOrEmpty(destPath)) { return(false); } using (WebP webp = new WebP()) { var bmp = webp.Load(sourcePath); var webp_byte = webp.LoadByte(sourcePath); if (compress) { bmp = webp.GetThumbnailFast(webp_byte, bmp.Width, bmp.Height); } else { bmp = webp.GetThumbnailQuality(webp_byte, bmp.Width, bmp.Height); } bmp.Save(destPath, System.Drawing.Imaging.ImageFormat.Png); } return(true); } catch { throw; } }
private static byte[] ResimYükle(Bitmap bmp) { using (var webp = new WebP()) { return(webp.EncodeLossy(bmp, (int)Kalite)); } }
private static Bitmap ReadWebP(String filePath) { using (WebP webp = new WebP()) { Bitmap bitmap = webp.Load(filePath); return(bitmap); } }
public static byte[] ResizeImage(Image image, int width, int height, ImageType type, bool keepRatio = true) { using (image) { if (keepRatio) { KeepRatioResise(image.Width, image.Height, ref width, ref height); } using (var newImage = new Bitmap(width, height)) using (var graphics = Graphics.FromImage(newImage)) { graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; if (type == ImageType.Jpeg) { graphics.Clear(Color.White); } graphics.DrawImage(image, new Rectangle(0, 0, width, height)); if (type == ImageType.Png) { using (var ms = new MemoryStream()) { newImage.Save(ms, ImageFormat.Png); return(ms.ToArray()); } } else if (type == ImageType.Webp) { byte[] rawWebP; using (WebP webp = new WebP()) { rawWebP = webp.EncodeLossy(newImage, 75, 0); return(rawWebP.ToArray()); } } else { using (var ms = new MemoryStream()) { var jpgEncoder = GetEncoder(ImageFormat.Jpeg); var myEncoder = Encoder.Quality; var myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(myEncoder, 75L); //70 qualidade para jpeg myEncoderParameters.Param[0] = myEncoderParameter; newImage.Save(ms, jpgEncoder, myEncoderParameters); return(ms.ToArray()); } } } } }
private void CreateWebPImage(IFormFile image, string filePath, int quality) { using (var webp = new WebP()) { var encoded = webp.EncodeLossy(new Bitmap(image.OpenReadStream()), quality); using (var webpFileStream = new FileStream(filePath, FileMode.Create)) webpFileStream.Write(encoded, 0, encoded.Length); } }
public static string ConvertWebPToTempPngFile(string webPPath) { string tempIcon = ApplicationDataUtils.GenerateNonExistentFilePath(extension: ".png"); IOUtils.EnsureParentDirExists(tempIcon); using (var webP = new WebP()) webP.Load(webPPath).Save(tempIcon, ImageFormat.Png); return(tempIcon); }
private async void LoadWebP(string url) { var renderer = await WebP.LoadTexturesAsync(url); if (renderer != null) { renderer.OnRender += texture => OnWebPRender(texture, url); } }
public static bool WriteWebP(Bitmap imageToConvert, string outputPath) { bool success = false; using (WebP webp = new WebP()) webp.Save(imageToConvert, outputPath, ExportSettings.imageQuality); success = true; return(success); }
/// <summary> /// Loads an image from disk into the supplied CachedImage object /// </summary> /// <param name="data">CachedImage object containg the filename to load</param> private static void LoadImage(object data) { bool done = false; int retry = 0; do { try { CachedImage ci = (CachedImage)data; if (Path.GetExtension(ci.sFilename) == ".webp") { using (WebP webp = new WebP()) ci.img = webp.Load(ci.sFilename); } else { ci.img = Image.FromFile(ci.sFilename); } done = true; } catch (Exception ex) { System.Console.WriteLine("ImageCache ERROR: " + ex.ToString()); System.Console.WriteLine("ImageCache exception HResult: " + ex.HResult); // only attempt retries if the reason for the failure was a sharing violation // [or a file not found] error; otherwise assume the error is permanent if (ex.HResult == unchecked ((int)0x80070020) // ERROR_SHARING_VIOLATION // || ex.HResult == unchecked((int)0x80070002) // ERROR_FILE_NOT_FOUND ) { System.Console.WriteLine(" ==> ERROR_SHARING_VIOLATION."); } else { done = true; } } if (!done) { retry++; System.Console.WriteLine(" failed to load image, attempting retry #" + retry); // minor delay as workaround for moved files being occasionally still locked by the AV System.Threading.Thread.Sleep(150); } } while ((retry < 3) && (done == false)); }
private void saveWebp_Click(object sender, EventArgs e) { Bitmap bmp = new Bitmap("D:\\temp.Jpeg"); //using (WebP webp = new WebP()) //webp.Save(bmp, 80, "test.webp"); //int re = 75; byte[] rawWebP = File.ReadAllBytes("D:\\temp.Jpeg"); using (WebP webp = new WebP()) rawWebP = webp.EncodeLossy(bmp, 75); File.WriteAllBytes("D:\\WebPimage.webp", rawWebP); //imageBytes = ImageToByteArray(img); }
/// <summary> /// Test GetPictureDistortion function /// </summary> private void ButtonMeasure_Click(object sender, EventArgs e) { try { if (this.pictureBox.Image == null) { MessageBox.Show("Please, load an reference image first"); } using (OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog()) { openFileDialog.Filter = "WebP images (*.webp)|*.webp"; openFileDialog.FileName = ""; if (openFileDialog.ShowDialog() == DialogResult.OK) { Bitmap source; Bitmap reference; float[] result; //Load Bitmaps source = (Bitmap)this.pictureBox.Image; using (WebP webp = new WebP()) reference = webp.Load(openFileDialog.FileName); //Measure PSNR using (WebP webp = new WebP()) result = webp.GetPictureDistortion(source, reference, 0); MessageBox.Show("Red: " + result[0] + "dB.\nGreen: " + result[1] + "dB.\nBlue: " + result[2] + "dB.\nAlpha: " + result[3] + "dB.\nAll: " + result[4] + "dB.", "PSNR"); //Measure SSIM using (WebP webp = new WebP()) result = webp.GetPictureDistortion(source, reference, 1); MessageBox.Show("Red: " + result[0] + "dB.\nGreen: " + result[1] + "dB.\nBlue: " + result[2] + "dB.\nAlpha: " + result[3] + "dB.\nAll: " + result[4] + "dB.", "SSIM"); //Measure LSIM using (WebP webp = new WebP()) result = webp.GetPictureDistortion(source, reference, 2); MessageBox.Show("Red: " + result[0] + "dB.\nGreen: " + result[1] + "dB.\nBlue: " + result[2] + "dB.\nAlpha: " + result[3] + "dB.\nAll: " + result[4] + "dB.", "LSIM"); } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonMeasure_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static string ConvertImageToTempWebPFile(Bitmap imageBitmap, bool lossless) { string tempIcon = ApplicationDataUtils.GenerateNonExistentFilePath(extension: ".webp"); IOUtils.EnsureParentDirExists(tempIcon); using (var webP = new WebP()) { File.WriteAllBytes( tempIcon, lossless ? webP.EncodeLossless(imageBitmap, speed: 9) : webP.EncodeLossy(imageBitmap, quality: 75, speed: 9) ); } return(tempIcon); }
/// <summary> /// 画像ファイルをWebPファイル形式に変換する /// </summary> /// <param name="imagePath"></param> /// <param name="quality"></param> /// <param name="isDeleteSourceFile"></param> /// <returns></returns> private static bool imageToWebp(string imagePath, int quality, bool isDeleteSourceFile) { var dirPath = Path.GetDirectoryName(imagePath); if (dirPath == null) { Log.Warn($"画像ファイルパスはフルパスで指定してください file={imagePath}"); return(false); } var fileName = ""; try { var outputPath = Path.Combine(dirPath, Path.GetFileNameWithoutExtension(imagePath) + ".webp"); if (File.Exists(outputPath)) { Log.Warn($"WebPファイルが既に存在するので削除 file={outputPath}"); File.Delete(outputPath); } fileName = Path.GetFileName(imagePath); Log.Info($"WebP変換開始 file={fileName}"); using (var bitmap = new Bitmap(imagePath)) { using var convBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height) , System.Drawing.Imaging.PixelFormat.Format32bppArgb); using WebP webp = new WebP(); webp.Save(convBitmap, outputPath, quality); } Log.Info($"WebP変換終了 file={fileName}"); if (isDeleteSourceFile) { File.Delete(imagePath); } } catch (Exception e) { Log.Error(e, $"WebP変換例外 file={fileName}"); return(false); } return(true); }
/// <summary> /// The Convert /// </summary> /// <param name="value">The <see cref="object"/></param> /// <param name="targetType">The <see cref="Type"/></param> /// <param name="parameter">The <see cref="object"/></param> /// <param name="culture">The <see cref="CultureInfo"/></param> /// <returns>The <see cref="object"/></returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null && value is Binary) { try { var ByteArray = value as Binary; var bmp = new BitmapImage(); using (var webp = new WebP()) bmp = Convert(webp.Decode(ByteArray.ToArray())); bmp.Freeze(); return(bmp); } catch (Exception) { } } return(null); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return null; } try { var imagesBytes = (byte[]) value; int hCode = imagesBytes.GetHashCode(); if (avatarCache.ContainsKey(hCode)) { return avatarCache[hCode]; } if (ImageUtils.GetImageFormat(imagesBytes) == Images.ImageFormat.Webp) { // WebP images using (WebP webp = new WebP()) { var bmp = webp.Decode(imagesBytes); var bitmapImage = BitmapToBitmapImage(bmp); avatarCache.Add(hCode, bitmapImage); return bitmapImage; } } else { // all other images var bitmapImage = ConvertByteArrayToBitmapImage(imagesBytes); avatarCache.Add(hCode, bitmapImage); return bitmapImage; } } catch(Exception) { return null; } }
public static async Task <byte[]> LoadUrlWebPImageAsync(string url) { if (string.IsNullOrEmpty(url)) { return(null); } System.Net.WebClient wc = new System.Net.WebClient(); wc.Headers.Add("Referer", "https://" + new Uri(url).Host); Byte[] MyData = await wc.DownloadDataTaskAsync(url); wc.Dispose(); WebP webP = new WebP(); Bitmap bitmap = webP.Decode(MyData); MemoryStream ms = new MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); byte[] data = ms.ToArray(); ms.Dispose(); return(data); }
/// <summary>convert jpeg image to webp</summary> /// <param name="sourcePath">valid source image path</param> /// <param name="destPath">destination image path that saved image there</param> /// <param name="quality">quality of converted image, between 0 and 100 <para>min quality : 0 </para><para>max quality : 100</para></param> /// <returns>return true if do correctly else return false</returns> public static bool JpegToWebP(string sourcePath, string destPath, int quality = 100) { try { if (String.IsNullOrEmpty(sourcePath) || String.IsNullOrEmpty(destPath)) { return(false); } if (quality <= 0 || quality > 100) { quality = 100; } using (WebP webp = new WebP()) { Bitmap bmp = new Bitmap(sourcePath); webp.Save(bmp, destPath, quality); } return(true); } catch { throw; } }
/// <summary>convert png image to webp</summary> /// <param name="sourceUrl">valid source image url</param> /// <param name="destPath">destination image path that saved image there</param> /// <param name="quality">quality of converted image, between 0 and 100 <para>min quality : 0 </para><para>max quality : 100</para></param> /// <returns>return true if do correctly else return false</returns> public static bool PngToWebPFromWeb(string sourceUrl, string destPath, int quality = 100) { try { if (String.IsNullOrEmpty(sourceUrl) || String.IsNullOrEmpty(destPath)) { return(false); } if (quality <= 0 || quality > 100) { quality = 100; } using (WebP webp = new WebP()) { Bitmap bmp = new Bitmap(Helper.DownloadImage(sourceUrl)); webp.Save(bmp, destPath, quality); } return(true); } catch { throw; } }