private Bitmap LoadBitmapUnlocked(string file_name) { Bitmap bitmapToUse = null; string upperFileName = file_name.ToUpper(); if (upperFileName.Contains(".WEBP")) { Console.WriteLine("Found WEBP :" + upperFileName); Imazen.WebP.SimpleDecoder decoder = new Imazen.WebP.SimpleDecoder(); var bytes = File.ReadAllBytes(file_name); var bitmap = decoder.DecodeFromBytes(bytes, bytes.Length); return(bitmap); } try { using (Bitmap bm = new Bitmap(file_name)) { bitmapToUse = new Bitmap(bm); } } catch (Exception) { //throw; } return(bitmapToUse); }
public void DownloadAvatar(Jid userId, string avatarId, string avatarType, RequestAvatarCallback finished) { PubSubIq dataiq = new PubSubIq(IqType.get, userId, Program.Jabber.conn.MyJID); dataiq.PubSub.Items = new Items("urn:xmpp:avatar:data"); dataiq.PubSub.Items.AddItem(new Item(avatarId)); Program.Jabber.conn.IqGrabber.SendIq(dataiq, (IqCB)((object sender_3, IQ result2, object unused_4) => { if (result2.Type != IqType.result) { finished(false, null); return; } Element data = result2.SelectSingleElement("data", true); byte[] imageBytes = Convert.FromBase64String(data.Value); Image img; switch (avatarType) { case "image/webp": var dec = new Imazen.WebP.SimpleDecoder(); img = dec.DecodeFromBytes(imageBytes, imageBytes.Length); break; default: img = Image.FromStream(new MemoryStream(imageBytes)); break; } string fileName = GetAvatarFilename(userId); img.Save(fileName, ImageFormat.Png); finished(true, fileName); })); }
public static FileInfo CalculateErrorInWebpLossless(FileInfo image1, FileInfo image2) { string newFile = $"{image1.DirectoryName}\\" + $"{(Directory.Exists(image1.DirectoryName + "\\result\\") ? $"result\\{Path.GetFileNameWithoutExtension(image1.Name)}\\" : "")}" + $"{Path.GetFileNameWithoutExtension(image1.Name)}_ErrorDiff_{Path.GetFileNameWithoutExtension(image2.Name)}.webp"; if (File.Exists(newFile)) { return(new FileInfo(newFile)); } Bitmap img1; if (image1.Extension == ".webp") { byte[] img1Bytes = File.ReadAllBytes(image1.FullName); img1 = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(img1Bytes, img1Bytes.Length); } else { img1 = new Bitmap(image1.FullName); } Bitmap img2; if (image2.Extension == ".webp") { byte[] img2Bytes = File.ReadAllBytes(image2.FullName); img2 = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(img2Bytes, img2Bytes.Length); } else { img2 = new Bitmap(image2.FullName); } Bitmap img3 = new Bitmap(img1.Width, img2.Height); for (int i = 0; i < img1.Height; i++) { for (int j = 0; j < img1.Width; j++) { Color p1 = img1.GetPixel(j, i); Color p2 = img2.GetPixel(j, i); int errR = Math.Abs(p2.R - p1.R); int errG = Math.Abs(p2.G - p1.G); int errB = Math.Abs(p2.B - p1.B); img3.SetPixel(j, i, Color.FromArgb(errR, errG, errB)); } } using var webPFileStream = new FileStream(newFile, FileMode.Create); new Imazen.WebP.SimpleEncoder().Encode(img3, webPFileStream, -1f); img1.Dispose(); img2.Dispose(); img3.Dispose(); return(new FileInfo(newFile)); }
public static FileInfo EncodeToJpeg(FileInfo input, string append, long quality, bool defaultQuality = false) { string newFile = $"{input.DirectoryName}\\" + $"{(Directory.Exists(input.DirectoryName + "\\result\\") ? $"result\\{Path.GetFileNameWithoutExtension(input.Name)}\\" : "")}" + $"{Path.GetFileNameWithoutExtension(input.Name)}_{append}.jpg"; if (File.Exists(newFile)) { return(new FileInfo(newFile)); } // Create a Bitmap object based on a BMP file. Bitmap image; if (input.Extension == ".webp") { byte[] img1Bytes = File.ReadAllBytes(input.FullName); image = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(img1Bytes, img1Bytes.Length); } else { image = new Bitmap(input.FullName); } // Get an ImageCodecInfo object that represents the JPEG codec. var myImageCodecInfo = GetEncoderInfo("image/jpeg"); // Create an Encoder object based on the GUID // for the Quality parameter category. Encoder myEncoder; if (!defaultQuality) { myEncoder = Encoder.Quality; } else { quality = 100; myEncoder = Encoder.Compression; } // Create an EncoderParameters object. // An EncoderParameters object has an array of EncoderParameter // objects. In this case, there is only one // EncoderParameter object in the array. var myEncoderParameters = new EncoderParameters(1); // Save the bitmap as a JPEG file var myEncoderParameter = new EncoderParameter(myEncoder, quality); myEncoderParameters.Param[0] = myEncoderParameter; image.Save(newFile, myImageCodecInfo, myEncoderParameters); image.Dispose(); return(new FileInfo(newFile)); }
private byte[] DecodeWebP(byte[] Data) { var Decoder = new Imazen.WebP.SimpleDecoder(); using (MemoryStream Output = new MemoryStream()) using (var Img = Decoder.DecodeFromBytes(Data, Data.LongLength)) { Img.Save(Output, ImageFormat.Png); return(Output.ToArray()); } }
// bitmapWillLockFile indicates whether holding onto Bitmap will hold lock on a file. public static Bitmap GetBitmap(string path, JpegRotationFinder shouldrotate, out bool bitmapWillLockFile) { Bitmap bitmap = null; try { if (ModeUtils.IsWebp(path)) { byte[] bytesData = File.ReadAllBytes(path); var decoder = new Imazen.WebP.SimpleDecoder(); bitmap = decoder.DecodeFromBytes(bytesData, bytesData.LongLength); bitmapWillLockFile = false; } else { bitmap = new Bitmap(path); bitmapWillLockFile = true; // some image files have custom resolutions, // I prefer seeing all files at the same resolution. bitmap.SetResolution(96.0f, 96.0f); } } catch (Exception e) { if (ModeUtils.IsWebp(path) && e.ToString().ToUpperInvariant().Contains("0x8007007E")) { Utils.MessageErr("It appears that the Visual C++ Redistributable " + "Packages for Visual Studio 2013 are not installed; please run " + "vcredist_x64.exe so that libwebp.dll can be used."); } Utils.MessageErr("Could not load the image " + path + Utils.NL + Utils.NL + Utils.NL + "Details: " + e.ToString(), true); if (bitmap != null) { bitmap.Dispose(); } bitmapWillLockFile = true; bitmap = new Bitmap(1, 1, PixelFormat.Format32bppPArgb); } if (shouldrotate != null && shouldrotate.ShouldRotate(path)) { bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone); } return(bitmap); }
public static Bitmap Load(string path) { string ext = Path.GetExtension(path); if (ext == ".webp") { byte[] bytes = File.ReadAllBytes(path); Imazen.WebP.SimpleDecoder decoder = new Imazen.WebP.SimpleDecoder(); return(decoder.DecodeFromBytes(bytes, bytes.Length)); } else { return(new Bitmap(path)); } }
public static void LongWork(IProgress <int> progress, int selectedOutput, int webpq, string outpath, DataGridViewRowCollection rows) { int p = 0; foreach (DataGridViewRow row in rows) { var extension = row.Cells[1].Value as string; var filepath = row.Cells[0].Value as string + extension; var filename = Path.GetFileNameWithoutExtension(filepath); byte[] buffer = File.ReadAllBytes(row.Cells[0].Value as string + row.Cells[1].Value as string); Bitmap bitmap = null; //check if current image is webp and encode if (extension.ToLowerInvariant().Contains("webp")) { var decoder = new Imazen.WebP.SimpleDecoder(); bitmap = decoder.DecodeFromBytes(buffer, buffer.LongLength); } else // If not, load file into bitmap { bitmap = new Bitmap(new MemoryStream(buffer)); } System.Drawing.Image img = bitmap; //If not saving as webp, use image.save with the appropriate format if (selectedOutput != 5) { img.Save(outpath + filename + $".{FormatExtensions[selectedOutput]}", ImageFormats[selectedOutput]); } else { //If saving as webp encode the file var encoder = new Imazen.WebP.SimpleEncoder(); FileStream outStream = new FileStream(outpath + filename + $".webp", FileMode.Create); encoder.Encode(bitmap, outStream, webpq); outStream.Close(); } p++; progress.Report(p); // report the progress to the ui thread if (Stop) { break; // if user requested to stop the conversion, break out of loop } } }
public static double CalculatePsnr(FileInfo image1, FileInfo image2) { Bitmap img1; if (image1.Extension == ".webp") { byte[] img1Bytes = File.ReadAllBytes(image1.FullName); img1 = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(img1Bytes, img1Bytes.Length); } else { img1 = new Bitmap(image1.FullName); } Bitmap img2; if (image2.Extension == ".webp") { byte[] img2Bytes = File.ReadAllBytes(image2.FullName); img2 = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(img2Bytes, img2Bytes.Length); } else { img2 = new Bitmap(image2.FullName); } double sumSq = 0; for (int i = 0; i < img1.Height; i++) { for (int j = 0; j < img1.Width; j++) { Color p1 = img1.GetPixel(j, i); Color p2 = img2.GetPixel(j, i); int errR = Math.Abs(p2.R - p1.R); int errG = Math.Abs(p2.G - p1.G); int errB = Math.Abs(p2.B - p1.B); sumSq += (double)(errR * errR) / 3 + (double)(errG * errG) / 3 + (double)(errB * errB) / 3; } } double mse = sumSq / (img1.Height * img1.Width); double psnr = 20 * Math.Log10(255d / Math.Sqrt(mse)); img1.Dispose(); img2.Dispose(); return(psnr); }
static void Main(string[] args) { if (args.Length < 1) { return; } int m_Width = 0, m_Height = 0; Bitmap paint = new Bitmap(10000, 10000, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(paint); byte[] data = File.ReadAllBytes(args[0]); byte[] segm = data.Take(64).ToArray(); for (int i = 0; i < 8; i++) { int offset = BitConverter.ToInt32(segm, i * 4); byte[] buff = new byte[16]; Buffer.BlockCopy(data, offset, buff, 0, buff.Length); for (int j = 0, k = 0; j < 16; j++, k += 0x77) { buff[j] -= (byte)k; } buff = new byte[BitConverter.ToUInt32(buff, 4) + 8]; Buffer.BlockCopy(data, offset, buff, 0, buff.Length); for (int j = 0, k = 0; j < 16; j++, k += 0x77) { buff[j] -= (byte)k; } Bitmap webp = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(buff, buff.Length); g.DrawImage(webp, 0, m_Height, webp.Width, webp.Height); if (m_Width < webp.Width) { m_Width = webp.Width; } m_Height += webp.Height; webp.Dispose(); } Bitmap image = new Bitmap(m_Width, m_Height, PixelFormat.Format32bppArgb); g = Graphics.FromImage(image); g.DrawImage(paint, 0, 0, new Rectangle(0, 0, m_Width, m_Height), GraphicsUnit.Pixel); image.Save(args[0]); image.Dispose(); paint.Dispose(); }
static void Main(string[] args) { try { if (args.Length > 0) { foreach (var arg in args) { var path = Path.GetFullPath(arg); var name = Path.GetFileNameWithoutExtension(arg); var folder = Path.Combine(AppContext.BaseDirectory, "output"); var newpath = Path.Combine(folder, $"{name}.png"); Directory.CreateDirectory(folder); var image = File.ReadAllBytes(path); var decoder = new Imazen.WebP.SimpleDecoder(); var bitmap = decoder.DecodeFromBytes(image, image.Length); bitmap.Save(newpath, ImageFormat.Png); bitmap.Dispose(); Console.WriteLine(name); } Console.WriteLine("Done."); } else { Console.WriteLine("Arguments error!"); Console.WriteLine("Webp2Png [path1] [path2] ..."); } Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public TikTokSimplifiedObject(AwemeStructV2 TikTokAwemeStructV2) { AuthorName = TikTokAwemeStructV2.author.nickname; var request = WebRequest.Create(TikTokAwemeStructV2.author.avatar_medium.url_list[0]); using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) { if (response.ContentType != "image/webp") { AuthorImage = Convert(System.Drawing.Image.FromStream(stream)); } else { using (MemoryStream ms = new MemoryStream()) { stream.CopyTo(ms); Bitmap webpConverted = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(ms.ToArray(), ms.Length); AuthorImage = Convert(webpConverted); } } } LikeNbr = int.Parse(TikTokAwemeStructV2.statistics.digg_count.ToString()); CommentNbr = int.Parse(TikTokAwemeStructV2.statistics.comment_count.ToString()); ShareNbr = int.Parse(TikTokAwemeStructV2.statistics.share_count.ToString()); var urlList = TikTokAwemeStructV2.video.play_addr.url_list; for (int j = 0; j < 3; j++) { if (urlList[j].ToString().Contains("api2.musical.ly")) { VideoUrl = urlList[j].ToString(); } } VideoDesc = makeNiceDesc(TikTokAwemeStructV2.desc); }
private void ImageExecute_Click(object sender, EventArgs e) { if (ImageValidate()) { return; } string directory = tImage.Text; DirectoryInfo dir = new DirectoryInfo(directory); List <string> imageTypes = new List <string>(); List <Img> listImage = new List <Img>(); string newFormat = cImageConvertTo.SelectedItem == null ? "" : cImageConvertTo.SelectedItem.ToString().ToLower(); if (cImageConvert.Checked) { imageTypes.AddRange(listImageConvert); } else { imageTypes.AddRange(new List <string> { "jpg", "png", "gif", "jpeg", "bmp", "jpe", "ico", "tif", "tiff", "jfif" }); } foreach (var file in dir.GetFiles()) { if (imageTypes.Contains(file.Extension.ToLower().Trim('.'))) { listImage.Add(new Img() { Name = file.Name, Extension = file.Extension.ToLower().Trim('.'), FullDir = file.FullName }); } } string strError = string.Empty; FileStream fStream; Image img; foreach (Img im in listImage) { // Load Image if (im.Extension == "webp") { var sE = new Imazen.WebP.SimpleDecoder(); using (var fS = new FileStream(im.FullDir, FileMode.Open)) { byte[] buffer = new byte[fS.Length]; fS.Read(buffer, 0, (int)fS.Length); img = sE.DecodeFromBytes(buffer, fS.Length); } im.Width = img.Width; im.Height = img.Height; } else { using (fStream = new FileStream(im.FullDir, FileMode.Open, FileAccess.Read)) { img = Image.FromStream(fStream); im.Width = img.Width; im.Height = img.Height; } } //Resize img = ResizeImage(img, im); // Convert if (cImageConvert.Checked) { FileInfo fI = new FileInfo(im.FullDir.Substring(0, im.FullDir.Length - im.Extension.Length) + newFormat); if (fI.Exists) { strError += " File already exists: " + im.Name.Substring(0, im.FullDir.Length - im.Extension.Length) + newFormat + Environment.NewLine; } else { var newFile = im.FullDir; if (!cImageOldExtension.Checked) { newFile = im.FullDir.Substring(0, im.FullDir.Length - im.Extension.Length) + newFormat; } im.Extension = newFormat; RemoveFile(newFile); if (newFormat == "webp") { using (var stream = new FileStream(newFile, FileMode.CreateNew)) { var sE = new Imazen.WebP.SimpleEncoder(); sE.Encode((Bitmap)img, stream, 96.6f); } } else { img.Save(newFile, im.Format); } if (cImageRemoveOrigin.Checked && !cImageOldExtension.Checked) { RemoveFile(im.FullDir); } } } else { EncoderParameters myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(Encoder.Quality, long.Parse(tImageQuality.Text ?? "98")); myEncoderParameters.Param[0] = myEncoderParameter; img.Save(im.FullDir, GetEncoder(im.Format), myEncoderParameters); } img.Dispose(); } if (strError != "") { MessageBox.Show(strError); } if (!cKeepAll.Checked) { listImageConvert.Clear(); lImageFrom.Items.Clear(); } MessageBox.Show("Finished."); }
public static string GenerateIcons(string path, string cfg_path, int random_integer, int integer, bool skip_entry = false) { string num = ""; double proportion; System.Drawing.Bitmap bitmap = null; System.Drawing.Bitmap bitmap1 = null; System.Drawing.Bitmap bitmap2 = null; if (path.ToLower().Contains(".png") || path.ToLower().Contains(".jpg") || path.ToLower().Contains(".jpeg")) { try { try { bitmap = new System.Drawing.Bitmap(path); } catch (Exception ex0) { byte[] buffer = new byte[12]; try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { fs.Read(buffer, 0, buffer.Length); fs.Close(); } if (buffer[0] == 82 && buffer[1] == 73 && buffer[2] == 70 && buffer[3] == 70 && buffer[8] == 87 && buffer[9] == 69 && buffer[10] == 66 && buffer[11] == 80) { //Webp Imazen.WebP.SimpleDecoder decoder = new Imazen.WebP.SimpleDecoder(); bitmap = decoder.DecodeFromBytes(File.ReadAllBytes(path), new System.IO.FileInfo(path).Length); } } catch (System.UnauthorizedAccessException ex1) { File.AppendAllText(cfg_path + "\\Error.log", "\r\n[Error: " + DateTime.Now + "] " + ex0.ToString()); } } bitmap1 = bitmap.Clone(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.PixelFormat.Format32bppPArgb);//BitmapHandler.CloneImage(ConvertToBitmap((BitmapSource)bitmap)); if (bitmap.Width > bitmap.Height) { proportion = bitmap.Width / 128; } else { proportion = bitmap.Height / 128; } if (bitmap1.Height > 128 && bitmap1.Width > 128) { bitmap2 = new System.Drawing.Bitmap(bitmap1, (int)(bitmap1.Width / proportion), (int)(bitmap1.Height / proportion)); } else { bitmap2 = bitmap1; } bitmap2.Save(cfg_path + "\\Cache\\thumbnail_" + random_integer + integer, System.Drawing.Imaging.ImageFormat.Png); if (!skip_entry) { File.AppendAllText(cfg_path + "\\Cache\\iconcache.db", path + "*" + "\\Cache\\thumbnail_" + random_integer + integer + "\r\n"); } num = "\\Cache\\thumbnail_" + random_integer + integer; bitmap = null; bitmap1 = null; bitmap2 = null; } catch (Exception ex) { } //bitmap2 = null; } else { IntPtr hIcon = Util.GetJumboIcon(Util.GetIconIndex(path)); // from native to managed try { using (System.Drawing.Icon ico = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(hIcon).Clone()) { // save to file (or show in a picture box) if (!IsSmallIcon(ico.ToBitmap())) { ico.ToBitmap().Save(cfg_path + "\\Cache\\icon_" + random_integer + integer, System.Drawing.Imaging.ImageFormat.Png); } else { System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(0, 0, 48, 48); System.Drawing.Image img = ico.ToBitmap(); Util.CropImage(img, cropRect).Save(cfg_path + "\\Cache\\icon_" + random_integer + integer, System.Drawing.Imaging.ImageFormat.Png); } if (!skip_entry) { File.AppendAllText(cfg_path + "\\Cache\\iconcache.db", path + "*" + "\\Cache\\icon_" + random_integer + integer + "\r\n"); } num = "\\Cache\\icon_" + random_integer + integer; } Util.Shell32.DestroyIcon(hIcon); // don't forget to cleanup } catch (Exception ex) { } } return(num); }