public void Save(Bitmap b, string filename, int defaultQuality) { using (var f = File.Create(filename)) { e.Encode(b, f, defaultQuality); } }
private void TestLosslessRoundtrip(Bitmap gdiBitmap) { var encoder = new SimpleEncoder(); var decoder = new SimpleDecoder(); using (var outStream = new System.IO.MemoryStream()) { encoder.Encode(gdiBitmap, outStream, -1); outStream.Close(); var webpBytes = outStream.ToArray(); var reloaded = decoder.DecodeFromBytes(webpBytes, webpBytes.LongLength); Assert.Equal(gdiBitmap.Height, reloaded.Height); Assert.Equal(gdiBitmap.Width, reloaded.Width); for (var y = 0; y < reloaded.Height; y++) { for (var x = 0; x < reloaded.Width; x++) { var expectedColor = gdiBitmap.GetPixel(x, y); var actualColor = reloaded.GetPixel(x, y); Assert.Equal(expectedColor, actualColor); } } } }
public void TestEncSimple() { Imazen.WebP.Extern.LoadLibrary.LoadWebPOrFail(); var encoder = new SimpleEncoder(); var fileName = "testimage.jpg"; var outFileName = "testimageout.webp"; File.Delete(outFileName); Bitmap mBitmap; FileStream outStream = new FileStream(outFileName, FileMode.Create); using (Stream BitmapStream = System.IO.File.Open(fileName, System.IO.FileMode.Open)) { Image img = Image.FromStream(BitmapStream); mBitmap = new Bitmap(img); encoder.Encode(mBitmap, outStream, 100); } FileInfo finfo = new FileInfo(outFileName); Assert.True(finfo.Exists); }
private void ProcessEntry(IArchiveEntry entry, IList <Stream> imageStreams, ZipArchive output, SimpleEncoder encoder) { using (var stream = entry.OpenEntryStream()) { var ms = new MemoryStream(); imageStreams.Add(ms); if (entry.Key.StartsWith("__MACOSX")) { return; } if (!entry.Key.EndsWith(".jpg") && !entry.Key.EndsWith(".png")) { stream.CopyTo(ms); output.AddEntry(entry.Key, ms); return; } Bitmap bits; try { bits = new Bitmap(stream); } catch (Exception e) { Logger.LogError("Error parsing bitmap: " + entry.Key); Logger.LogDebug(e, LogLevel.Error); return; } if (bits.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb) { var newBits = ChangePixelFormat(bits); bits.Dispose(); bits = newBits; } try { encoder.Encode(bits, ms, Quality); output.AddEntry(entry.Key + ".webp", ms); } catch (Exception e) { Logger.LogError("Error encoding entry: " + entry.Key); Logger.LogDebug(e, LogLevel.Error); } finally { bits.Dispose(); } } }
private void ProcessEntry(Stream stream, string entryKey, ZipArchive output, SimpleEncoder encoder) { if (entryKey.StartsWith("__MACOSX")) { return; } if (!entryKey.EndsWith(".jpg") && !entryKey.EndsWith(".png")) { output.AddEntry(entryKey, stream); return; } Bitmap bits; try { bits = new Bitmap(stream); } catch (Exception e) { Logger.LogError("Error parsing bitmap: " + entryKey); Logger.LogDebug(e, LogLevel.Error); return; } if (bits.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb) { var newBits = ChangePixelFormat(bits); bits.Dispose(); bits = newBits; } try { using (var ms = new MemoryStream()) { encoder.Encode(bits, ms, Quality); stream.Dispose(); stream = new MemoryStream(); ms.WriteTo(stream); output.AddEntry(Path.ChangeExtension(entryKey, "webp"), stream); } } catch (Exception e) { Logger.LogError("Error encoding entry: " + entryKey); Logger.LogDebug(e, LogLevel.Error); } finally { bits.Dispose(); } }
public static Response GetSyncWebpStream(Comic comic, Guid id, IResponseFormatter response) { string tmpPath = System.IO.Path.GetTempPath(); var zipPath = comic.FilePath; string extractPath = tmpPath + "\\" + comic.Id + "\\"; extractPath = Path.GetFullPath(extractPath); // Check if original image is in the cache. string fileName = Path.GetFileName(zipPath); MemoryStream cbz_stream = null; cbz_stream = ImageCache.Instance.LoadFromCache(fileName, false, true); var comic_xml = new MemoryStream(); var encoder = new SimpleEncoder(); if (cbz_stream == null) { //Opening ComicArchive and getting ComicInfo.xml for use in new cbz file using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (var entry in archive.Entries) { if (entry.FullName.Equals("ComicInfo.xml", StringComparison.OrdinalIgnoreCase)) { using (var entry_stream = entry.Open()) { entry_stream.CopyTo(comic_xml); } } } } comic_xml.Seek(0, SeekOrigin.Begin); var ms = new MemoryStream(); using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true)) { var demoFile = zipArchive.CreateEntry("ComicInfo.xml"); using (var entreyStream = demoFile.Open()) { comic_xml.CopyTo(entreyStream); } for (int i = 0; i <= comic.PageCount - 1; i++) { MemoryStream stream = null; string org_filename = string.Format("{0}-p{1}.jpg", id, i); stream = ImageCache.Instance.LoadFromCache(org_filename, false, false); if (stream == null) { // Image is not in the cache, get it via ComicRack. var bytes = BCR.GetPageImageBytes(id, i); if (bytes == null) { return(HttpStatusCode.NotFound); } stream = new MemoryStream(bytes); // Always save the original page to the cache ImageCache.Instance.SaveToCache(org_filename, stream, false, false); } stream.Seek(0, SeekOrigin.Begin); Bitmap image = new Bitmap(stream); var result = i.ToString().PadLeft(5, '0'); string webpFileName = string.Format("P{0}.webp", result); string combined = Path.Combine(extractPath, webpFileName); var entry = zipArchive.CreateEntry(webpFileName, CompressionLevel.Fastest); Int32 webpquality = Database.Instance.GlobalSettings.webp_quality; using (var entryStream = entry.Open()) { try { encoder.Encode(image, entryStream, webpquality); } catch //(Exception e) { // MessageBox.Show(e.ToString()); } } stream.Dispose(); } } ImageCache.Instance.SaveToCache(fileName, ms, false, true); ms.Seek(0, SeekOrigin.Begin); StreamResponse resp = new StreamResponse(() => ms, "application/zip"); return(resp .WithHeader("Content-Disposition", "attachment; filename=" + fileName) .AsAttachment(fileName, "application/zip")); } else { StreamResponse resp = new StreamResponse(() => cbz_stream, "application/zip"); return(resp .WithHeader("Content-Disposition", "attachment; filename=" + fileName) .AsAttachment(fileName, "application/zip")); } }
public static Response GetSyncWebp(Comic comic, Guid id, IResponseFormatter response) { string tmpPath = System.IO.Path.GetTempPath(); var zipPath = comic.FilePath; string extractPath = tmpPath + "\\" + comic.Id + "\\"; extractPath = Path.GetFullPath(extractPath); var encoder = new SimpleEncoder(); // Check if original image is in the cache. string fileName = Path.GetFileName(zipPath); MemoryStream cbz_stream = null; cbz_stream = ImageCache.Instance.LoadFromCache(fileName, false, true); if (cbz_stream == null) { // If directory does not exist, create it. if (!Directory.Exists(extractPath)) { Directory.CreateDirectory(extractPath); } using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (var entry in archive.Entries) { if (entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) { string combined = Path.Combine(extractPath, entry.FullName); entry.ExtractToFile(combined, true); } } } //System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath); // Check if original image is in the cache. for (int i = 0; i <= comic.PageCount - 1; i++) { MemoryStream stream = null; string org_filename = string.Format("{0}-p{1}.jpg", id, i); stream = ImageCache.Instance.LoadFromCache(org_filename, false, false); if (stream == null) { // Image is not in the cache, get it via ComicRack. var bytes = BCR.GetPageImageBytes(id, i); if (bytes == null) { return(HttpStatusCode.NotFound); } stream = new MemoryStream(bytes); // Always save the original page to the cache ImageCache.Instance.SaveToCache(org_filename, stream, false, false); } stream.Seek(0, SeekOrigin.Begin); Bitmap image = new Bitmap(stream); var result = i.ToString().PadLeft(5, '0'); string webpFileName = string.Format("P{0}.webp", result); string combined = Path.Combine(extractPath, webpFileName); Int32 webpquality = Database.Instance.GlobalSettings.webp_quality; using (var saveImageStream = System.IO.File.Open(combined, FileMode.Create)) { try { encoder.Encode(image, saveImageStream, webpquality); } catch //(Exception e) { // MessageBox.Show(e.ToString()); } } stream.Dispose(); } string zipName = tmpPath + "\\" + comic.Id + ".cbz"; //check if zipfile exists if so delete it. try { if (File.Exists(zipName)) { File.Delete(zipName); } //Creates a new, blank zip file to work with - the file will be //finalized when the using statement completes using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create)) { foreach (string file in Directory.GetFiles(extractPath)) { newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file)); } } } catch (Exception) { return(HttpStatusCode.NotFound); } // Always save the original page to the cache var resp_stream = new MemoryStream(File.ReadAllBytes(zipName)); ImageCache.Instance.SaveToCache(fileName, resp_stream, false, true); StreamResponse resp = new StreamResponse(() => resp_stream, "application/zip"); return(resp .WithHeader("Content-Disposition", "attachment; filename=" + fileName) .AsAttachment(fileName, "application/zip")); } else { StreamResponse resp = new StreamResponse(() => cbz_stream, "application/zip"); return(resp .WithHeader("Content-Disposition", "attachment; filename=" + fileName) .AsAttachment(fileName, "application/zip")); } }
public ActionResult UploadBannerFiles() { List <string> Uploaded = new List <string>(); if (Request.Files.Count != 0) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; var fileName = "Image_" + DateTime.Now.ToShortDateString().Replace('/', '_') + "_" + DateTime.Now.ToShortTimeString().Replace(':', '_') + "_" + Path.GetFileName(file.FileName.Replace(' ', '_')); var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName); //Image img = Image.FromStream(file.InputStream, true, true); //img.Save(path); file.SaveAs(path); Uploaded.Add($"{HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Host + ":" + HttpContext.Request.Url.Port}/Uploads/" + fileName); //thumbnailing System.Drawing.Image image = System.Drawing.Image.FromFile(path); Bitmap tmpResized = ResizeImage(image, 720, 200); string newpath = Path.Combine(Server.MapPath("~/Uploads/Banner/Normal/"), fileName.Replace(fileName.Split('.').Last(), "webp")); using (tmpResized) { using (var saveImageStream = System.IO.File.Open(newpath, FileMode.Create)) { var encoder = new SimpleEncoder(); encoder.Encode(tmpResized, saveImageStream, 80); } } tmpResized = ResizeImage(image, 270, 345); newpath = Path.Combine(Server.MapPath("~/Uploads/Banner/Sidbar/"), fileName.Replace(fileName.Split('.').Last(), "webp")); using (tmpResized) { using (var saveImageStream = System.IO.File.Open(newpath, FileMode.Create)) { var encoder = new SimpleEncoder(); encoder.Encode(tmpResized, saveImageStream, 80); } } tmpResized = ResizeImage(image, 870, 175); newpath = Path.Combine(Server.MapPath("~/Uploads/Banner/Big/"), fileName.Replace(fileName.Split('.').Last(), "webp")); using (tmpResized) { using (var saveImageStream = System.IO.File.Open(newpath, FileMode.Create)) { var encoder = new SimpleEncoder(); encoder.Encode(tmpResized, saveImageStream, 80); } } } return(Json(new JsonResults() { HasValue = true, Html = RenderViewToString(this.ControllerContext, "_UploadedImages", Uploaded), Message = string.Join(",", Uploaded) })); } else { return(Json(new JsonResults() { HasValue = false })); } }