public static IEnumerable<Bitmap> SeperateGif(string gifPath) { using (var gifImage = Image.FromFile(gifPath)) { var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); var frameCount = gifImage.GetFrameCount(dimension); for (var index = 0; index < frameCount; index++) { gifImage.SelectActiveFrame(dimension, index); yield return (Bitmap)gifImage.Clone(); } } }
void Awake() { var gifImage = Image.FromFile(loadingGifPath); var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); int frameCount = gifImage.GetFrameCount(dimension); for (int i = 0; i < frameCount; i++) { gifImage.SelectActiveFrame(dimension, i); var frame = new Bitmap(gifImage.Width, gifImage.Height); System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty); var frameTexture = new Texture2D(frame.Width, frame.Height); for (int x = 0; x < frame.Width; x++) for (int y = 0; y < frame.Height; y++) { System.Drawing.Color sourceColor = frame.GetPixel(x, y); frameTexture.SetPixel(frame.Width - 1 - x, y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped } frameTexture.Apply(); gifFrames.Add(frameTexture); } }
public PlainImage(awt.Image image, awt.Image [] thumbnails, ImageFormat format, float xRes, float yRes, FrameDimension dimension) { _nativeObject = image; _thumbnails = thumbnails; _imageFormat = format; _xResolution = xRes; _yResolution = yRes; _dimension = dimension; }
public static int LoadFromMemory(Image memoryImage, string name, long lColorKey, int iMaxWidth, int iMaxHeight) { Log.Debug("TextureManager: load from memory: {0}", name); string cacheName = name; string cacheKey = name.ToLower(); CachedTexture cached; if (_cacheTextures.TryGetValue(cacheKey, out cached)) { return(cached.Frames); } if (memoryImage == null) { return(0); } if (memoryImage.FrameDimensionsList == null) { return(0); } if (memoryImage.FrameDimensionsList.Length == 0) { return(0); } try { CachedTexture newCache = new CachedTexture(); newCache.Name = cacheName; FrameDimension oDimension = new FrameDimension(memoryImage.FrameDimensionsList[0]); newCache.Frames = memoryImage.GetFrameCount(oDimension); if (newCache.Frames != 1) { return(0); } //load gif into texture using (MemoryStream stream = new MemoryStream()) { memoryImage.Save(stream, ImageFormat.Png); ImageInformation info2 = new ImageInformation(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); Texture texture = TextureLoader.FromStream( GUIGraphicsContext.DX9Device, stream, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, Format.A8R8G8B8, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)lColorKey, ref info2); newCache.Width = info2.Width; newCache.Height = info2.Height; newCache.texture = new CachedTexture.Frame(cacheName, texture, 0); } memoryImage.SafeDispose(); memoryImage = null; newCache.Disposed += new EventHandler(cachedTexture_Disposed); _cacheTextures[cacheKey] = newCache; Log.Debug("TextureManager: added: memoryImage " + " total count: " + _cacheTextures.Count + ", mem left (MB): " + ((uint)GUIGraphicsContext.DX9Device.AvailableTextureMemory / 1048576)); return(newCache.Frames); } catch (Exception ex) { Log.Error("TextureManager: exception loading texture memoryImage"); Log.Error(ex); } return(0); }
private void ShowImage(bool force = false) { if (Resource == null) { return; } if (SavedSize.Equals(Size) && force == false) { return; } SavedSize = Size; var ctrls = Controls.OfType <PictureBox>().ToList(); foreach (var ctrl in ctrls) { Controls.Remove(ctrl); } if (pb == null) { pb = new PictureBox(); pb.SizeMode = PictureBoxSizeMode.StretchImage; } try { byte[] imageBytes = Convert.FromBase64String(Resource.Content); if (Resource.Type == (int)WebresourceType.Vector) { using (MemoryStream ms = new MemoryStream(imageBytes)) { using (StreamReader reader = new StreamReader(ms)) { using (var xmlStream = new MemoryStream(Encoding.Default.GetBytes(reader.ReadToEnd()))) { xmlStream.Position = 0; SvgDocument svgDoc = SvgDocument.Open <SvgDocument>(xmlStream); pb.Height = 32; pb.Width = 32; pb.Image = svgDoc.Draw(); // pb.Image = svgDoc.Draw(32, 32); pb.Location = new Point( Width / 2 - pb.Width / 2, Height / 2 - pb.Height / 2); } } } } else { using (MemoryStream ms = new MemoryStream(imageBytes)) { var image = Image.FromStream(ms, true, true); FrameDimension frameDimensions = new FrameDimension(image.FrameDimensionsList[0]); int frames = image.GetFrameCount(frameDimensions); if (frames > 1) { lblError.Text = @"This image is an animated GIF and cannot be rendered"; pnlError.Visible = true; } else { if (image.Height == 32 && image.Width == 32) { pb.Image = image; pb.Height = pb.Image.Size.Height; pb.Width = pb.Image.Size.Width; pb.BackColor = Color.Blue; lblError.Text = @"Entity Large icon detected (size: 32x32): A blue background has been added to provide a better display of the icon"; pnlError.Visible = true; } else if (image.Height == 71 && image.Width == 85) { Bitmap bm = new Bitmap(205, 83); using (Graphics gr = Graphics.FromImage(bm)) { gr.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle(0, 0, 205, 83); gr.FillRectangle(new SolidBrush(Color.FromArgb(45, 116, 234)), rect); gr.DrawImage(image, new Point(110, 6)); } pb.Image = bm; pb.Height = 83; pb.Width = 205; lblError.Text = @"SiteMap Area icon detected (size: 85x71): A blue background has been added to provide a better display of the icon"; pnlError.Visible = true; } else { pb.Image = image; pb.Height = pb.Image.Size.Height; pb.Width = pb.Image.Size.Width; pnlError.Visible = false; } if (pb.Width > Width) { pb.Width = Width; } pb.Location = new Point( Width / 2 - pb.Width / 2, Height / 2 - pb.Height / 2); } } } Controls.Add(pb); } catch (Exception error) { lblError.Text = $@"An error occured while loading this web resource: {error.Message}"; pnlError.Visible = true; } }
private static double[] BBB(string sourceFilePath) { //string filePath = sourceFilePath + @"ClearOutside.tif"; string filePath = sourceFilePath + @"Background.tif"; Image image = Image.FromFile(filePath); int frames = 0; Guid[] guid = image.FrameDimensionsList; FrameDimension fd = new FrameDimension(guid[0]); frames = image.GetFrameCount(fd); double[] output = new double[frames]; for (int i = 0; i < frames; i++) { image.SelectActiveFrame(fd, i); Bitmap myBitmap = new Bitmap(image); int[] signal = new int[myBitmap.Width * myBitmap.Height]; int number = 0; int width = myBitmap.Width; int height = myBitmap.Height; BitmapData bmpData = myBitmap.LockBits(new Rectangle(0, 0, myBitmap.Width, myBitmap.Height), ImageLockMode.ReadOnly, myBitmap.PixelFormat); Parallel.For(0, width, Xcount => { Parallel.For(0, height, Ycount => { int offset = Xcount * bmpData.Stride + Ycount * (bmpData.Stride / bmpData.Width); int r = Marshal.ReadByte(bmpData.Scan0, offset + 2); if (r > 0) { signal[Xcount + width * Ycount] = r; } }); }); Array.Sort(signal); for (int index = signal.Length - 1; index > 0; index--) { if (signal[index] > 0) { number++; } else { break; } } double acc = 0; for (int j = 0; j < signal.Length; j++) { if (signal[j] > 0) { acc = acc + signal[j]; } } output[i] = acc / number; //output[i] = averageRealSignal(signal, number); //Color pixelColor = myBitmap.GetPixel(277, 314); Console.Write("Process for background: {0}/{1}\n", i, frames); } return(output); }
public GifImage(string path) { gifImage = Image.FromFile(path); //initialize dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); //gets the GUID frameCount = gifImage.GetFrameCount(dimension); //total frames in the animation }
public Game01() { InitializeComponent(); Image asdf = (Image)resoureManager.GetObject("walking"); gamePanel.Size = asdf.Size; ClientSize = asdf.Size; gamePanel.Location = new Point(0, 0); Controls.Add(gamePanel); //SetAnimatie(); FormClosing += sluit; gamePanel.Paint += (sender, args) => { FrameDimension dimension = new FrameDimension(asdf.FrameDimensionsList[0]); // Number of frames int frameCount = asdf.GetFrameCount(dimension); asdf.SelectActiveFrame(dimension, i); Text = frameCount.ToString() + ", " + i; //Text = asdf.GetFrameCount(dimension).ToString(); args.Graphics.FillRectangle(Brushes.Black, loc.X, loc.Y, 20, 20); }; KeyDown += (sender, args) => { animating = true; if (args.KeyCode == Keys.Up) { up = true; } if (args.KeyCode == Keys.Down) { down = true; } if (args.KeyCode == Keys.Left) { left = true; } if (args.KeyCode == Keys.Right) { right = true; } if (up && down) { up = false; down = false; } if (left && right) { left = false; right = false; } }; KeyUp += (sender, args) => { if (args.KeyCode == Keys.Up) { up = false; } if (args.KeyCode == Keys.Down) { down = false; } if (args.KeyCode == Keys.Left) { left = false; } if (args.KeyCode == Keys.Right) { right = false; } }; tr = new Thread(Animate); tr.Start(); }
//Merge Method public void Merge(string MergeFileName, string source) { //Set its Image Format as TIFF ImageCodecInfo codecInfo = GetCodecInfo(TIFF_CODEC); //Load the Document FileStream fs = new FileStream(source, FileMode.OpenOrCreate); Image image = Image.FromStream(fs); //Get file frame/pages FrameDimension frameDim = new FrameDimension(image.FrameDimensionsList[0]); if (newdocument == true) { //Set its Image Type encoderParams = new EncoderParameters(2); encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame); encoderParams.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ENCODING_SCHEME); //Check if selected pages is null or 0 value if (SelectedPages != null) { //for each frame/pages create the new document for (int i = 0; i < image.GetFrameCount(frameDim); i++) { //check whether selected pages is not greater than the file pages if (Pages.Length >= (i + 1)) { //Selected image frame image.SelectActiveFrame(frameDim, Pages[i]); //check whether file is new document if (newfile == true) { //create new filename Document = image; //save Document.Save(MergeFileName, codecInfo, encoderParams); encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); newfile = false; newdocument = false; } else { //append the document depending on the selected frame from the original image Document.SaveAdd(image, encoderParams); } } } fs.Close(); } } else { //Check if selected pages is null or 0 value if (SelectedPages != null) { //for each frame/pages create the new document for (int i = 0; i < image.GetFrameCount(frameDim); i++) { //check whether selected pages is not greater than the file pages if (Pages.Length >= (i + 1)) { //Selected image frame image.SelectActiveFrame(frameDim, Pages[i]); //check whether file is new document //append the document depending on the selected frame from the original image Document.SaveAdd(image, encoderParams); } } fs.Close(); } } }
/// <summary> /// Merge one or more image or document files into a single PDF /// Supported Formats: bmp, gif, jpg, jpeg, png, tif, tiff, pdf (including multi-page tiff and pdf files) /// Original code: https://www.ryadel.com/en/merge-multiple-gif-png-jpg-pdf-image-files-single-pdf-file-asp-net-c-sharp-core-itextsharp/ /// </summary> public bool MergeIntoPDF(string outputPdfFile, bool replace = false, params ByteArrayInfo[] infoArray) { _lasterror = ""; _laststacktrace = ""; // If output file exists and not replacing, bail out. if (File.Exists(outputPdfFile)) { if (!replace) { throw new Exception(String.Format("Output PDF file {0} already exists and replace not selected. Process cancelled.", outputPdfFile)); } else { File.Delete(outputPdfFile); } } // If we do have a single PDF file, write out the original file data without doing anything if (infoArray.Length == 1 && infoArray[0].FileExtension.Trim('.').ToLower() == "pdf") { File.WriteAllBytes(outputPdfFile, infoArray[0].Data); return(true); } // patch to fix the "PdfReader not opened with owner password" error. // ref.: https://stackoverflow.com/questions/17691013/pdfreader-not-opened-with-owner-password-error-in-itext PdfReader.unethicalreading = true; using (Document doc = new Document()) { doc.SetPageSize(PageSize.LETTER); using (var ms = new MemoryStream()) { // PdfWriter wri = PdfWriter.GetInstance(doc, ms); using (PdfCopy pdf = new PdfCopy(doc, ms)) { doc.Open(); foreach (ByteArrayInfo info in infoArray) { try { doc.NewPage(); Document imageDocument = null; PdfWriter imageDocumentWriter = null; switch (info.FileExtension.Trim('.').ToLower()) { case "bmp": case "gif": case "jpg": case "jpeg": case "png": using (imageDocument = new Document()) { using (var imageMS = new MemoryStream()) { using (imageDocumentWriter = PdfWriter.GetInstance(imageDocument, imageMS)) { imageDocument.Open(); if (imageDocument.NewPage()) { var image = iTextSharp.text.Image.GetInstance(info.Data); image.Alignment = Element.ALIGN_CENTER; image.ScaleToFit(doc.PageSize.Width - 10, doc.PageSize.Height - 10); if (!imageDocument.Add(image)) { throw new Exception("Unable to add image to page!"); } imageDocument.Close(); imageDocumentWriter.Close(); using (PdfReader imageDocumentReader = new PdfReader(imageMS.ToArray())) { var page = pdf.GetImportedPage(imageDocumentReader, 1); pdf.AddPage(page); imageDocumentReader.Close(); } } } } } break; case "tif": case "tiff": //Get the frame dimension list from the image of the file using (var imageStream = new MemoryStream(info.Data)) { using (System.Drawing.Image tiffImage = System.Drawing.Image.FromStream(imageStream)) { //get the globally unique identifier (GUID) Guid objGuid = tiffImage.FrameDimensionsList[0]; //create the frame dimension FrameDimension dimension = new FrameDimension(objGuid); //Gets the total number of frames in the .tiff file int noOfPages = tiffImage.GetFrameCount(dimension); //get the codec for tiff files ImageCodecInfo ici = null; foreach (ImageCodecInfo i in ImageCodecInfo.GetImageEncoders()) { if (i.MimeType == "image/tiff") { ici = i; } } foreach (Guid guid in tiffImage.FrameDimensionsList) { for (int index = 0; index < noOfPages; index++) { FrameDimension currentFrame = new FrameDimension(guid); tiffImage.SelectActiveFrame(currentFrame, index); using (MemoryStream tempImg = new MemoryStream()) { //var encoder = new TiffBitmapEncoder(); //encoder.Compression = TiffCompressOption.Zip; //encoder.Frames.Add(BitmapFrame.Create(image)); //encoder.Save(stream); // Encoder parameters for CCITT G4 //EncoderParameters eps = new EncoderParameters(1); //eps.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionCCITT4); //tiffImage.Save(tempImg,ImageCodecInfo.GetImageEncoders( ImageFormat.Tiff,eps); // Original code saved as TIFF before adding to PDF. PNG is smaller //tiffImage.Save(tempImg, ImageFormat.Tiff); // Save image as PNG before writing to Ong file. Png format is smaller tiffImage.Save(tempImg, ImageFormat.Png); using (imageDocument = new Document()) { using (var imageMS = new MemoryStream()) { using (imageDocumentWriter = PdfWriter.GetInstance(imageDocument, imageMS)) { imageDocument.Open(); if (imageDocument.NewPage()) { var image = iTextSharp.text.Image.GetInstance(tempImg.ToArray()); //image.CompressionLevel = Element.CCITTG4; // Set image DPI //image.SetDpi(100,100); image.Alignment = Element.ALIGN_CENTER; image.ScaleToFit(doc.PageSize.Width - 10, doc.PageSize.Height - 10); if (!imageDocument.Add(image)) { throw new Exception("Unable to add image to page!"); } imageDocument.Close(); imageDocumentWriter.Close(); using (PdfReader imageDocumentReader = new PdfReader(imageMS.ToArray())) { var page = pdf.GetImportedPage(imageDocumentReader, 1); pdf.AddPage(page); imageDocumentReader.Close(); } } } } } } } } } } break; case "pdf": using (var reader = new PdfReader(info.Data)) { for (int i = 0; i < reader.NumberOfPages; i++) { pdf.AddPage(pdf.GetImportedPage(reader, i + 1)); } pdf.FreeReader(reader); reader.Close(); } break; default: // not supported image format: // skip it (or throw an exception if you prefer) throw new Exception(String.Format("Unsupported image format for file {0}", info.FileName)); } } catch (Exception e) { e.Data["FileName"] = info.FileName; _lasterror = e.Message; _laststacktrace = e.StackTrace; return(false); } } if (doc.IsOpen()) { doc.Close(); } // Write output to the new consolidated PDF file File.WriteAllBytes(outputPdfFile, ms.GetBuffer()); return(true); } } } }
public int SelectActiveFrame(FrameDimension dimension, int frameIndex) { throw new NotImplementedException(); }
public int GetFrameCount(FrameDimension dimension) { throw new NotImplementedException(); }
public int SelectActiveFrame(FrameDimension dimension, int frameIndex) {}
public int GetFrameCount(FrameDimension dimension) {}
public void Guid_ReturnsExpected(Guid expected, FrameDimension frameDimension) { Assert.Equal(expected, frameDimension.Guid); }
public void ToString_ReturnsExpected(string expected, FrameDimension imageFormat) { Assert.Equal(expected, imageFormat.ToString()); }
/// <summary> /// Export the selected frames into a folder /// </summary> public void ExportFrames() { // Get the current time to use in the iterator: DateTime t = DateTime.Now; // Get the path and trim the leading characters: string path = _formatForm.SavePath.Trim(' ', '\\'); // Get the filename and extension: string fileName = _formatForm.FileName; string extension = _formatForm.Extension; // Get a valid imageformat to use in the savind process: ImageFormat format = GetFormatByString(extension); // Get the frame range: Point range = tlc_timeline.GetRange(); range.X -= 1; // Unload the GIF from the memory, so we can work it with: LoadGif(""); // Load the GIF file: Image m = Image.FromFile(CurrentGif.GifPath); // Get the frame dimension to advance the frames: FrameDimension frameDimension = new FrameDimension(m.FrameDimensionsList[0]); try { for (int x = range.X; x < (range.X + 1) + range.Y; x++) { // Get the name: string name = fileName; // Replace the tokens: while (name.Contains("{%i}")) { name = name.Replace("{%i}", (x + 1) + ""); } while (name.Contains("{%h}")) { name = name.Replace("{%h}", "" + t.Hour); } while (name.Contains("{%m}")) { name = name.Replace("{%m}", "" + t.Minute); } while (name.Contains("{%s}")) { name = name.Replace("{%s}", "" + t.Second); } // Create the bitmap and the graphics: Bitmap b = new Bitmap(m.Width, m.Height); Graphics g = Graphics.FromImage(b); // Advance to the desired frame: m.SelectActiveFrame(frameDimension, x); // Draw the image: g.DrawImageUnscaled(m, 0, 0); // Save the image down to the path with the given format: b.Save(path + "\\" + name + extension, format); // Dispose the bitmap and the graphics: g.Dispose(); b.Dispose(); } } catch (Exception e) { ErrorBox.Show("Error exporting frames: " + e.Message, "Error", e.StackTrace); } // Dispose the GIF: m.Dispose(); // Reload the GIF: LoadGif(CurrentGif.GifPath); }
private static IEnumerator <float> _BitmapToText(Image image, Action <FrameData> handle, float scale = 0f, bool shapeCorrection = true, float waitTime = .1f) { if (image == null) { yield break; } var wait = TimeSpan.FromSeconds(waitTime); var size = 0f; var dim = new FrameDimension(image.FrameDimensionsList[0]); var frames = image.GetFrameCount(dim); var fails = 0; for (var index = 0; index < frames; index++) { var time = DateTime.Now; image.SelectActiveFrame(dim, index); if (image.Size.Height * image.Size.Width > 10000) { throw new Exception("The image was too large. Please use an image with less that 10,000 pixels. Your image doesn't need to be more than 100x100."); } if (size == 0f) { size = Convert.ToInt32(scale == 0f ? Math.Floor((-.47 * (((image.Size.Width + image.Size.Height) / 2 > 60 ? 45 : (image.Width + image.Height) / 2))) + 28.72) : scale); } Bitmap bitmap; if (shapeCorrection) { bitmap = new Bitmap(image, new Size(Convert.ToInt32(image.Size.Width * (1 + .03 * size)), image.Size.Height)); } else { bitmap = new Bitmap(image); } var text = "<size=" + size + "%>"; var pastPixel = new Color(); var threshold = 0f; while ((System.Text.Encoding.Unicode.GetByteCount(text) > 32768 || text == "<size=" + size + "%>") && threshold < 5f) { text = "<size=" + size + "%>"; //I need to figure out how to use bitmap data, but GetPixel is fine for now for (var i = 0; i < bitmap.Height; i++) { for (var j = 0; j < bitmap.Width; j++) { var pixel = bitmap.GetPixel(j, i); var colorString = "#" + pixel.R.ToString("X2") + pixel.G.ToString("X2") + pixel.B.ToString("X2") + pixel.A.ToString("X2"); if (!pixel.Equals(pastPixel)) { if (threshold == 0f || (i == 0 && j == 0)) { text += ((i == 0 && j == 0) ? "" : "</color>") + "<color=" + colorString + ">█"; } else { var d1 = Math.Abs(pixel.GetHue() - pastPixel.GetHue()); var d2 = Math.Abs(pixel.GetSaturation() - pastPixel.GetSaturation()); var d3 = Math.Abs(pixel.GetBrightness() - pastPixel.GetBrightness()); var diff = (((d1 > 180 ? 360 - d1 : d1) * .755f) + (d2 * 2f) + (d3 * .7f)) / 3; if (diff > threshold) { text += ((i == 0 && j == 0) ? "" : "</color>") + "<color=" + colorString + ">█"; } else { pixel = pastPixel; text += "█"; } } } else { text += "█"; } pastPixel = pixel; if (j == bitmap.Width - 1) { text += "\\n"; } } } if (!text.EndsWith("</color>\\n") && !text.EndsWith("</color>")) { text += "</color>"; } text += "</size>"; threshold += .5f; } if (System.Text.Encoding.Unicode.GetByteCount(text) > 32768) { fails++; continue; } handle(new FrameData(text)); if (waitTime != 0f) { var diff = DateTime.Now - time; if (diff < wait) { yield return(Timing.WaitForSeconds((float)(wait - diff).TotalSeconds)); } } } image.Dispose(); handle(new FrameData(null) { Last = true }); if (frames == 1 && fails > 0) { throw new Exception("The image is too large to display."); } if (fails > 0) { throw new Exception(fails + " frames have been dropped while attempting to display this image."); } }
public virtual void ThumbByCut(Stream sourceStream, Stream ouputStream, int width, int height, bool highQuality) { Image source = null; try { source = System.Drawing.Image.FromStream(sourceStream); //先等比裁剪 int tw = width; int th = height; if (tw == 0 && th != 0) { tw = (int)(source.Width * (double)th / source.Height); } else if (th == 0 && tw != 0) { th = (int)(source.Height * (double)width / source.Width); } else if (th == 0 && tw == 0) { th = source.Height; tw = source.Width; } int cutWidth = 0; int cutHeight = 0; int bywWidth = source.Width; int bywHeight = (int)(source.Width * (double)th / tw); if (bywHeight < 1) { bywHeight = 1; } int byhWidth = (int)(source.Height * (double)tw / th); if (byhWidth < 1) { byhWidth = 1; } int byhHeight = source.Height; if (bywHeight > source.Height)//如果根据宽度裁剪得到的高度超过原始高度 { cutWidth = byhWidth; cutHeight = byhHeight; } else if (byhWidth > source.Width) //如果根据高度裁剪得到的宽度高过原始宽度 { cutWidth = bywWidth; cutHeight = bywHeight; } else { //如果两个依据都符合,则根据面积的大小判断,面积越大,精确度越高 if ((bywWidth * bywHeight) > (byhWidth * byhHeight)) { cutWidth = bywWidth; cutHeight = bywHeight; } else { cutWidth = byhWidth; cutHeight = byhHeight; } } //根据中心点,得到裁剪的起始地址 int x = (int)((double)source.Width / 2 - (double)cutWidth / 2); int y = (int)((double)source.Height / 2 - (double)cutHeight / 2); if (x < 0) { x = 0; } if (y < 0) { y = 0; } sourceStream.Seek(0, SeekOrigin.Begin); Bitmap ora_Img = new Bitmap(sourceStream); List <Frame> frames = new List <Frame>(); foreach (Guid guid in ora_Img.FrameDimensionsList) { FrameDimension frameDimension = new FrameDimension(guid); int frameCount = ora_Img.GetFrameCount(frameDimension); byte[] buffer = ora_Img.GetPropertyItem(20736).Value; for (int i = 0; i < frameCount; i++) { if (ora_Img.SelectActiveFrame(frameDimension, i) == 0) { int delay = BitConverter.ToInt32(buffer, i * 4); System.IO.MemoryStream stream = new System.IO.MemoryStream(); source = Image.FromHbitmap(ora_Img.GetHbitmap()) as Bitmap; Color backColor = Color.White; Bitmap img = new Bitmap(cutWidth, cutHeight, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(img)) { Rectangle destRect = new Rectangle(0, 0, cutWidth, cutHeight); g.DrawImage(source, destRect, x, y, cutWidth, cutHeight, GraphicsUnit.Pixel); using (MemoryStream ms = new MemoryStream()) { img.Save(ms, ImageFormat.Jpeg); source.Dispose(); source = Image.FromStream(ms); //再缩放 ImageZip(cutWidth, cutHeight, ref width, ref height); img = new Bitmap(width, height); //img.SetResolution(72f, 72f); img.SetResolution(source.HorizontalResolution, source.VerticalResolution); using (Graphics gdiobj = Graphics.FromImage(img)) { SetQuality(gdiobj); gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height); Rectangle destrect = new Rectangle(0, 0, width, height); gdiobj.DrawImage(source, destrect, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel); } } } Frame frame = new Frame(img, delay, backColor); frames.Add(frame); } } } AnimatedGifEncoder gif = new AnimatedGifEncoder(); gif.Start(ouputStream); gif.SetRepeat(0); for (int i = 0; i < frames.Count; i++) { gif.SetDelay(frames[i].Delay); gif.AddFrame(frames[i].Img); } gif.Finish(); } catch (Exception ex) { throw ex; } finally { source.Dispose(); } }
internal static void EnsureSave(Image image, string filename, Stream dataStream) { if (image.RawFormat.Equals(ImageFormat.Gif)) { bool animatedGif = false; Guid[] dimensions = image.FrameDimensionsList; foreach (Guid guid in dimensions) { FrameDimension dimension = new FrameDimension(guid); if (dimension.Equals(FrameDimension.Time)) { animatedGif = image.GetFrameCount(FrameDimension.Time) > 1; break; } } if (animatedGif) { try { Stream created = null; long lastPos = 0; if (dataStream != null) { lastPos = dataStream.Position; dataStream.Position = 0; } try { if (dataStream == null) { created = dataStream = File.OpenRead(filename); } image._rawData = new byte[(int)dataStream.Length]; dataStream.Read(image._rawData, 0, (int)dataStream.Length); } finally { if (created != null) { created.Close(); } else { dataStream.Position = lastPos; } } } // possible exceptions for reading the filename catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } // possible exceptions for setting/getting the position inside dataStream catch (NotSupportedException) { } catch (ObjectDisposedException) { } // possible exception when reading stuff into dataStream catch (ArgumentException) { } } } }
/// <summary> /// 以填充模式缩略图片 /// </summary> public virtual void ThumbByFill(Stream sourceStream, Stream ouputStream, int width, int height, bool highQuality) { Image source = Image.FromStream(sourceStream); if (source.RawFormat.Guid != ImageFormat.Gif.Guid) { throw new IOException(string.Format("文件不是GIF格式的图片!")); } if (width == 0 || (width > 200 && width > source.Width)) { width = source.Width; //做200的限制,实际文件超过200的,就以实际为大小 } if (height == 0 || (height > 200 && height > source.Height)) { height = source.Height; //做200的限制,实际文件超过200的,就以实际为大小 } int x = 0, y = 0, tw, th; //先等比缩放 if (source.Width > source.Height) { //宽大于高,以宽等比缩放 tw = source.Width > width ? width : source.Width; th = (int)(source.Height * (double)tw / (double)source.Width); if (th > height)//得到的结果比需要的高度高,则根据高度缩放 { th = source.Height > height ? height : source.Height; tw = (int)(source.Width * (double)th / (double)source.Height); } } else { //高大于宽,以高等比缩放 th = source.Height > height ? height : source.Height; tw = (int)(source.Width * (double)th / (double)source.Height); if (tw > width)//得到的结果比需要的宽度宽,则根据宽度缩放 { tw = source.Width > width ? width : source.Width; th = (int)(source.Height * (double)tw / (double)source.Width); } } if (tw < width) { x = (width - tw) / 2; } if (th < height) { y = (height - th) / 2; } sourceStream.Seek(0, SeekOrigin.Begin); Bitmap ora_Img = new Bitmap(sourceStream); List <Frame> frames = new List <Frame>(); foreach (Guid guid in ora_Img.FrameDimensionsList) { FrameDimension frameDimension = new FrameDimension(guid); int frameCount = ora_Img.GetFrameCount(frameDimension); byte[] buffer = ora_Img.GetPropertyItem(20736).Value; for (int i = 0; i < frameCount; i++) { if (ora_Img.SelectActiveFrame(frameDimension, i) == 0) { int delay = BitConverter.ToInt32(buffer, i * 4); System.IO.MemoryStream stream = new System.IO.MemoryStream(); source = Image.FromHbitmap(ora_Img.GetHbitmap()) as Bitmap; Color backColor = Color.White; Bitmap img = new Bitmap(width, height); img.SetResolution(72f, 72f); img.SetResolution(source.HorizontalResolution, source.VerticalResolution); using (Graphics gdiobj = Graphics.FromImage(img)) { SetQuality(gdiobj); gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height); Rectangle destrect = new Rectangle(x, y, tw, th); gdiobj.DrawImage(source, destrect, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel); } Frame frame = new Frame(img, delay, backColor); frames.Add(frame); } } } AnimatedGifEncoder gif = new AnimatedGifEncoder(); gif.Start(ouputStream); gif.SetRepeat(0); for (int i = 0; i < frames.Count; i++) { gif.SetDelay(frames[i].Delay); gif.AddFrame(frames[i].Img); } gif.Finish(); }
public static void WriteImage(Stream inStream, Stream outStream, int boundWidth, int boundHeight, RenderModes mode) { Bitmap bmpSrc = null, bmpTrg = null; try { bmpSrc = new Bitmap(inStream); // convert TIFF to BMP, use only the first page FrameDimension fd = new FrameDimension(bmpSrc.FrameDimensionsList[0]); bmpSrc.SelectActiveFrame(fd, 0); // crop/fit/stretch int imageHeight = bmpSrc.Height, imageWidth = bmpSrc.Width, targetWidth, targetHeight; if (boundWidth < 0) { boundWidth = imageWidth; } if (boundHeight < 0) { boundHeight = imageHeight; } if (boundWidth != imageWidth || boundHeight != imageHeight) { switch (mode) { case RenderModes.RenderMode_Stretch: bmpTrg = new Bitmap(bmpSrc, new Size(boundWidth, boundHeight)); break; case RenderModes.RenderMode_Fit: targetWidth = imageWidth; targetHeight = imageHeight; float scale = 1F; // a. panel is greater than image: grow if (boundHeight > imageHeight && boundWidth > imageWidth) { scale = Math.Min((float)boundWidth / imageWidth, (float)boundHeight / imageHeight); targetHeight = Math.Min((int)((float)imageHeight * scale), boundHeight); targetWidth = Math.Min((int)((float)imageWidth * scale), boundWidth); } // b. image is greater than panel: shrink else { scale = Math.Max((float)imageWidth / boundWidth, (float)imageHeight / boundHeight); targetWidth = Math.Min((int)((float)imageWidth / scale), boundWidth); targetHeight = Math.Min((int)((float)imageHeight / scale), boundHeight); } bmpTrg = new Bitmap(bmpSrc, new Size(targetWidth, targetHeight)); break; case RenderModes.RenderMode_Crop: targetWidth = Math.Min(boundWidth, imageWidth); targetHeight = Math.Min(boundHeight, imageHeight); bmpTrg = bmpSrc.Clone( new Rectangle(0, 0, targetWidth, targetHeight), bmpSrc.PixelFormat ); break; } bmpTrg.Save(outStream, ImageFormat.Png); } else { bmpSrc.Save(outStream, ImageFormat.Png); } } finally { if (bmpTrg != null) { bmpTrg.Dispose(); } if (bmpSrc != null) { bmpSrc.Dispose(); } GC.Collect(); } }
/// <summary> /// 保留全图的缩放(但会使图像变形) /// </summary> /// <param name="sourceStream"></param> /// <param name="ouputStream"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="format"></param> /// <param name="highQuality"></param> public virtual void ThumbByFull(Stream sourceStream, Stream ouputStream, int width, int height, bool highQuality) { Image source = null; try { source = System.Drawing.Image.FromStream(sourceStream); ImageZip(source.Width, source.Height, ref width, ref height); sourceStream.Seek(0, SeekOrigin.Begin); Bitmap ora_Img = new Bitmap(sourceStream); List <Frame> frames = new List <Frame>(); foreach (Guid guid in ora_Img.FrameDimensionsList) { FrameDimension frameDimension = new FrameDimension(guid); int frameCount = ora_Img.GetFrameCount(frameDimension); byte[] buffer = ora_Img.GetPropertyItem(20736).Value; for (int i = 0; i < frameCount; i++) { if (ora_Img.SelectActiveFrame(frameDimension, i) == 0) { int delay = BitConverter.ToInt32(buffer, i * 4); System.IO.MemoryStream stream = new System.IO.MemoryStream(); source = Image.FromHbitmap(ora_Img.GetHbitmap()) as Bitmap; Color backColor = Color.White; Bitmap img = new Bitmap(width, height); //img.SetResolution(72f, 72f); img.SetResolution(source.HorizontalResolution, source.VerticalResolution); using (Graphics gdiobj = Graphics.FromImage(img)) { SetQuality(gdiobj); gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height); Rectangle destrect = new Rectangle(0, 0, width, height); gdiobj.DrawImage(source, destrect, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel); } Frame frame = new Frame(img, delay, backColor); frames.Add(frame); } } } AnimatedGifEncoder gif = new AnimatedGifEncoder(); gif.Start(ouputStream); gif.SetRepeat(0); for (int i = 0; i < frames.Count; i++) { gif.SetDelay(frames[i].Delay); gif.AddFrame(frames[i].Img); } gif.Finish(); } catch (Exception ex) { throw ex; } finally { source.Dispose(); } }
public static void Mark(string file, string waterImg, int markx, int marky, float transparence, int guanggao) { Image img = Image.FromFile(file); foreach (Guid guid in img.FrameDimensionsList) { FrameDimension dimension = new FrameDimension(guid); if (img.GetFrameCount(dimension) > 1) { return; } } try { int picWidth = img.Width; int picHeight = img.Height; if (img.Width > 550) { //picWidth = 550; //picHeight = (picWidth * img.Height) / img.Width; //Image.GetThumbnailImageAbort callback2 = null; //System.Drawing.Image image4 = new Bitmap(picWidth, picHeight); //Graphics graphicsPic = Graphics.FromImage(image4); //graphicsPic.InterpolationMode = InterpolationMode.High; //graphicsPic.SmoothingMode = SmoothingMode.HighQuality; //graphicsPic.Clear(Color.White); } Image image = Image.FromFile(waterImg); float[][] numArray2 = new float[5][]; float[] numArray3 = new float[5]; numArray3[0] = 1f; numArray2[0] = numArray3; float[] numArray4 = new float[5]; numArray4[1] = 1f; numArray2[1] = numArray4; float[] numArray5 = new float[5]; numArray5[2] = 1f; numArray2[2] = numArray5; float[] numArray6 = new float[5]; numArray6[3] = transparence; numArray2[3] = numArray6; float[] numArray7 = new float[5]; numArray7[4] = 1f; numArray2[4] = numArray7; float[][] newColorMatrix = numArray2; ColorMatrix matrix = new ColorMatrix(newColorMatrix); ImageAttributes imageAttr = new ImageAttributes(); imageAttr.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Default); Bitmap bitmap = new Bitmap(picWidth, picHeight, PixelFormat.Format24bppRgb); bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution); Graphics graphics = Graphics.FromImage(bitmap); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.DrawImage(img, new Rectangle(0, 0, picWidth, picHeight), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel); if (guanggao == 0) { //if ((image.Width > img.Width) || (image.Height > img.Height)) //{ // Image.GetThumbnailImageAbort callback = null; // Image image2 = image.GetThumbnailImage(img.Width / 4, (image.Height * img.Width) / image.Width, callback, new IntPtr()); // graphics.DrawImage(image2, new Rectangle(markx, marky, image2.Width, image2.Height), 0, 0, image2.Width, image2.Height, GraphicsUnit.Pixel, imageAttr); // image2.Dispose(); // graphics.Dispose(); // MemoryStream stream = new MemoryStream(); // bitmap.Save(stream, ImageFormat.Jpeg); // img = Image.FromStream(stream); // return img; //} graphics.DrawImage(image, new Rectangle(img.Width - image.Width, img.Height - image.Height, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttr); } graphics.Dispose(); img.Dispose(); image.Dispose(); File.Delete(file); bitmap.Save(file, ImageFormat.Jpeg); bitmap.Dispose(); } catch { } }
// TODO: move to separate file public static void WriteImage(Stream inStream, Stream outStream, int panelWidth, int panelHeight, RenderModes mode) { Bitmap bmpSrc = null, bmpTrg = null; try { inStream.Position = 0; bmpSrc = new Bitmap(inStream); // convert TIFF to BMP, use only the first page FrameDimension fd = new FrameDimension(bmpSrc.FrameDimensionsList[0]); bmpSrc.SelectActiveFrame(fd, 0); // crop/fit/stretch int imageHeight = bmpSrc.Height, imageWidth = bmpSrc.Width, targetWidth, targetHeight; if (panelWidth <= 0) { panelWidth = imageWidth; } if (panelHeight <= 0) { panelHeight = imageHeight; } if (panelWidth != imageWidth || panelHeight != imageHeight) { switch (mode) { case RenderModes.RenderMode_Stretch: if (panelWidth <= 120 && panelHeight <= 120) { bmpTrg = new Bitmap(bmpSrc.GetThumbnailImage(panelWidth, panelHeight, () => false, IntPtr.Zero)); } else { bmpTrg = new Bitmap(bmpSrc, new Size(panelWidth, panelHeight)); } break; case RenderModes.RenderMode_Fit: targetWidth = imageWidth; targetHeight = imageHeight; float scale = 1F; // a. panel is greater than image: grow if (panelHeight > imageHeight && panelWidth > imageWidth) { scale = Math.Min((float)panelWidth / imageWidth, (float)panelHeight / imageHeight); targetHeight = Math.Min((int)((float)imageHeight * scale), panelHeight); targetWidth = Math.Min((int)((float)imageWidth * scale), panelWidth); } // b. image is greater than panel: shrink else { scale = Math.Max((float)imageWidth / panelWidth, (float)imageHeight / panelHeight); targetWidth = Math.Min((int)((float)imageWidth / scale), panelWidth); targetHeight = Math.Min((int)((float)imageHeight / scale), panelHeight); } if (targetWidth <= 120 && targetHeight <= 120) { bmpTrg = new Bitmap(bmpSrc.GetThumbnailImage(targetWidth, targetHeight, () => false, IntPtr.Zero)); } else { bmpTrg = new Bitmap(bmpSrc, new Size(targetWidth, targetHeight)); } break; case RenderModes.RenderMode_Crop: targetWidth = Math.Min(panelWidth, imageWidth); targetHeight = Math.Min(panelHeight, imageHeight); bmpTrg = bmpSrc.Clone( new Rectangle(0, 0, targetWidth, targetHeight), bmpSrc.PixelFormat ); break; } bmpTrg.Save(outStream, ImageFormat.Png); } else { bmpSrc.Save(outStream, ImageFormat.Png); } outStream.Seek(0, SeekOrigin.Begin); } finally { if (bmpTrg != null) { bmpTrg.Dispose(); } if (bmpSrc != null) { bmpSrc.Dispose(); } GC.Collect(); } }
public static int Load(string fileNameOrg, long lColorKey, int iMaxWidth, int iMaxHeight, bool persistent) { string fileName = GetFileName(fileNameOrg); string cacheKey = fileName.ToLower(); if (String.IsNullOrEmpty(fileName)) { return(0); } CachedTexture cached; if (_cacheTextures.TryGetValue(cacheKey, out cached)) { return(cached.Frames); } string extension = Path.GetExtension(fileName).ToLower(); if (extension == ".gif") { Image theImage = null; try { try { theImage = ImageFast.FromFile(fileName); } catch (FileNotFoundException) { Log.Warn("TextureManager: texture: {0} does not exist", fileName); return(0); } catch (Exception) { Log.Warn("TextureManager: Fast loading texture {0} failed using safer fallback", fileName); theImage = Image.FromFile(fileName); } if (theImage != null) { CachedTexture newCache = new CachedTexture(); newCache.Name = fileName; FrameDimension oDimension = new FrameDimension(theImage.FrameDimensionsList[0]); newCache.Frames = theImage.GetFrameCount(oDimension); int[] frameDelay = new int[newCache.Frames]; for (int num2 = 0; (num2 < newCache.Frames); ++num2) { frameDelay[num2] = 0; } // Getting Frame duration of an animated Gif image try { int num1 = 20736; PropertyItem item1 = theImage.GetPropertyItem(num1); if (item1 != null) { byte[] buffer1 = item1.Value; for (int num2 = 0; (num2 < newCache.Frames); ++num2) { frameDelay[num2] = (((buffer1[(num2 * 4)] + (256 * buffer1[((num2 * 4) + 1)])) + (65536 * buffer1[((num2 * 4) + 2)])) + (16777216 * buffer1[((num2 * 4) + 3)])); } } } catch (Exception) {} for (int i = 0; i < newCache.Frames; ++i) { theImage.SelectActiveFrame(oDimension, i); //load gif into texture using (MemoryStream stream = new MemoryStream()) { theImage.Save(stream, ImageFormat.Png); ImageInformation info2 = new ImageInformation(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); Texture texture = TextureLoader.FromStream( GUIGraphicsContext.DX9Device, stream, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, Format.A8R8G8B8, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)lColorKey, ref info2); newCache.Width = info2.Width; newCache.Height = info2.Height; newCache[i] = new CachedTexture.Frame(fileName, texture, (frameDelay[i] / 5) * 50); } } theImage.SafeDispose(); theImage = null; newCache.Disposed += new EventHandler(cachedTexture_Disposed); if (persistent && !_persistentTextures.ContainsKey(cacheKey)) { _persistentTextures[cacheKey] = true; } _cacheTextures[cacheKey] = newCache; //Log.Info(" TextureManager:added:" + fileName + " total:" + _cache.Count + " mem left:" + GUIGraphicsContext.DX9Device.AvailableTextureMemory.ToString()); return(newCache.Frames); } } catch (Exception ex) { Log.Error("TextureManager: exception loading texture {0} - {1}", fileName, ex.Message); } return(0); } try { int width, height; Texture dxtexture = LoadGraphic(fileName, lColorKey, iMaxWidth, iMaxHeight, out width, out height); if (dxtexture != null) { CachedTexture newCache = new CachedTexture(); newCache.Name = fileName; newCache.Frames = 1; newCache.Width = width; newCache.Height = height; newCache.texture = new CachedTexture.Frame(fileName, dxtexture, 0); //Log.Info(" texturemanager:added:" + fileName + " total:" + _cache.Count + " mem left:" + GUIGraphicsContext.DX9Device.AvailableTextureMemory.ToString()); newCache.Disposed += new EventHandler(cachedTexture_Disposed); if (persistent && !_persistentTextures.ContainsKey(cacheKey)) { _persistentTextures[cacheKey] = true; } _cacheTextures[cacheKey] = newCache; return(1); } } catch (Exception) { return(0); } return(0); }
/// <summary> /// upload shape /// </summary> /// <param name="fileNamePath">The file's full path</param> /// <param name="uriString">Save url</param> private static void UpLoadFile(string fileNamePath, string uriString) { string NewFileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1); string fileNameExt = NewFileName.Substring(NewFileName.LastIndexOf(".") + 1); if (uriString.EndsWith("/") == false) { uriString = uriString + "/"; } if (NewFileName.Contains(".gif") || NewFileName.Contains(".Gif") || NewFileName.Contains(".GIF")) { try { Image gif = Image.FromFile(fileNamePath); FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧) int count = gif.GetFrameCount(fd); //以Jpeg格式保存各帧 gif.SelectActiveFrame(fd, 0); gif.Save(uriString + NewFileName.Substring(0, NewFileName.IndexOf(".")) + ".jpg", ImageFormat.Jpeg); return; } catch { return; } } try { uriString = uriString + NewFileName; WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); //FileStream fs = OpenFile(); BinaryReader r = new BinaryReader(fs); byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(uriString, "PUT"); if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); } else { MsgBox.Warning("At present can't be written documents !"); } postStream.Close(); } catch { //MsgBox.Warning("Document failed to upload, please try again later!"); } }
public imageUtil(string path) { gifImage = Image.FromFile(path); dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); frameCount = gifImage.GetFrameCount(dimension); }
private void OutputGenerate(ControllerContext context) { var reportFile = context.HttpContext.Server.MapPath(_reportFile); var oldReport = context.HttpContext.Request.QueryString["__oldrdlReport"]; DeletePreGeneratedFile(oldReport); if (!File.Exists(reportFile)) { OutputJson(new GenerateReasult { Code = 1, Message = "报表" + _reportFile + "不存在!" }, context); return; } var rv = new ReportViewer(); rv.LocalReport.ReportPath = reportFile; var settings = new ReportSettings(); if (_reportBuilder != null) { try { _reportBuilder(rv.LocalReport, settings); } catch (Exception ex) { OutputJson(new GenerateReasult { Code = 2, Message = ex.Message }, context); return; } } try { rv.LocalReport.Refresh(); var reportFileId = Guid.NewGuid().ToString(); var img = _exportFiles.ElementAt(0); exportTargetFile(reportFileId, img.Value, img.Key, rv, settings); Task.Factory.StartNew(args => { try { if (!(args is Tuple <string, ReportViewer, ReportSettings> tuple)) { return; } for (var i = 1; i < _exportFiles.Count; i++) { var cfg = _exportFiles.ElementAt(i); exportTargetFile(tuple.Item1, cfg.Value, cfg.Key, tuple.Item2, tuple.Item3); } } // ReSharper disable once EmptyGeneralCatchClause catch { } }, new Tuple <string, ReportViewer, ReportSettings>(reportFileId, rv, settings)); var tiffImg = Image.FromFile(Path.Combine(Path.GetTempPath(), reportFileId + ".tif")); var guid = tiffImg.FrameDimensionsList[0]; var dimension = new FrameDimension(guid); var pageCount = tiffImg.GetFrameCount(dimension); tiffImg.Dispose(); OutputJson(new GenerateReasult { Code = 0, FileId = reportFileId, PageCount = pageCount, DownloadName = settings.DownLoadFileName }, context); } catch (Exception ex) { OutputJson(new GenerateReasult { Code = 3, Message = GetFirstExceptionMessage(ex) }, context); } }
///------------------------------------------------------------------------------ /// <summary> /// マルチフレームの画像ファイルを頁ごとに分割する:OpenCVバージョン</summary> /// <param name="InPath"> /// 画像ファイル入力パス</param> /// <param name="outPath"> /// 分割後出力パス</param> /// <returns> /// true:分割を実施, false:分割ファイルなし</returns> ///------------------------------------------------------------------------------ private bool MultiTif_New(string InPath, string outPath) { ////スキャン出力画像を確認 //if (System.IO.Directory.GetFiles(InPath, "*.tif").Count() == 0) //{ // MessageBox.Show("OCR変換処理対象の画像ファイルが指定フォルダ " + InPath + " に存在しません", "スキャン画像確認", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // return false; //} // 出力先フォルダがなければ作成する if (System.IO.Directory.Exists(outPath) == false) { System.IO.Directory.CreateDirectory(outPath); } // 出力先フォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため) foreach (string files in System.IO.Directory.GetFiles(outPath, "*")) { System.IO.File.Delete(files); } int _pageCount = 0; string fnm = string.Empty; // マルチTIFを分解して画像ファイルをTRAYフォルダへ保存する foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif")) { //TIFFのImageCodecInfoを取得する ImageCodecInfo ici = GetEncoderInfo("image/tiff"); if (ici == null) { return(false); } using (System.IO.FileStream tifFS = new System.IO.FileStream(files, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { Image gim = Image.FromStream(tifFS); FrameDimension gfd = new FrameDimension(gim.FrameDimensionsList[0]); //全体のページ数を得る int pageCount = gim.GetFrameCount(gfd); for (int i = 0; i < pageCount; i++) { gim.SelectActiveFrame(gfd, i); // ファイル名(日付時間部分) string fName = string.Format("{0:0000}", DateTime.Today.Year) + string.Format("{0:00}", DateTime.Today.Month) + string.Format("{0:00}", DateTime.Today.Day) + string.Format("{0:00}", DateTime.Now.Hour) + string.Format("{0:00}", DateTime.Now.Minute) + string.Format("{0:00}", DateTime.Now.Second); _pageCount++; // ファイル名設定 fnm = outPath + fName + string.Format("{0:000}", _pageCount) + ".tif"; EncoderParameters ep = null; // 圧縮方法を指定する ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4); // 画像保存 gim.Save(fnm, ici, ep); ep.Dispose(); } } } // InPathフォルダの全てのtifファイルを削除する foreach (var files in System.IO.Directory.GetFiles(InPath, "*.tif")) { System.IO.File.Delete(files); } return(true); }
/// <summary> /// Awake is called before start. Here we convert the gif files to single textures if needed. /// This only works in the editor /// </summary> void Awake() { // If we're running in the Unity editor and not unity webplayer nor webgl #if UNITY_EDITOR && !UNITY_WEBPLAYER && !UNITY_WEBGL // Loop through gif files from folder .../Assets/Chatbot/Unity Implementation/Emoticons/ foreach (string _file in Directory.GetFiles(Application.dataPath + "/Chatbot/Unity Implementation/Emoticons/")) { // Declare frame variable Texture2D _gifFrame = null; // Try to load image from resources _gifFrame = Resources.Load("Chatbot/Unity Implementation/Emoticons/" + (_file.Remove(_file.LastIndexOf("."))).Substring(_file.LastIndexOf("/") + 1) + "_0", typeof(Texture2D)) as Texture2D; // Check if gif has already been split into single images if (_gifFrame == null && _file.Substring(_file.LastIndexOf(".") + 1).ToLower() == "gif") { // We need to parse the gif and save the frames saperately // Initialize gif function var gifImage = Image.FromFile(_file); var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); int frameCount = gifImage.GetFrameCount(dimension); for (int i = 0; i < frameCount; i++) { gifImage.SelectActiveFrame(dimension, i); var frame = new Bitmap(gifImage.Width, gifImage.Height); System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty); var frameTexture = new Texture2D(frame.Width, frame.Height); for (int x = 0; x < frame.Width; x++) { for (int y = 0; y < frame.Height; y++) { System.Drawing.Color sourceColor = frame.GetPixel(x, y); frameTexture.SetPixel(x, frame.Height - 1 - y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped } } // Apply texture changes frameTexture.Apply(); // Encode texture into PNG byte[] _pngBytes = frameTexture.EncodeToPNG(); // Write Texture as png in Resources Folder System.IO.File.WriteAllBytes(Application.dataPath + "/Chatbot/Resources/Chatbot/Unity Implementation/Emoticons/" + (_file.Remove(_file.LastIndexOf("."))).Substring(_file.LastIndexOf("/") + 1) + "_" + i + ".png", _pngBytes); } } } #if (!UNITY_4_0 && !UNITY_4_0_1) // Causes a freeze in Unity 4.0. Thus changes are first applied upon restart. // Save changed/new assets AssetDatabase.SaveAssets(); // Refresh database AssetDatabase.Refresh(); #endif #endif // Try to load frames from resources var _resourcesArray = Resources.LoadAll("Chatbot/Unity Implementation/Emoticons", typeof(Texture2D)); // Create texture array Texture2D[] _resourcesGifFrames = new Texture2D[_resourcesArray.Length]; // Loop through ressources array for (var i = 0; i < _resourcesArray.Length; i++) { // Store in texture array _resourcesGifFrames[i] = _resourcesArray[i] as Texture2D; } // Create new list of emoticons List <string> _emoticonList = new List <string>(); // Loop through all frames foreach (Texture2D _currentFrame in _resourcesGifFrames) { // Check if emoticon is new if (!_emoticonList.Contains(_currentFrame.name.Remove(_currentFrame.name.LastIndexOf("_")))) { // Add emoticon to list _emoticonList.Add(_currentFrame.name.Remove(_currentFrame.name.LastIndexOf("_"))); } } // Now Loop through emoticons foreach (string _currentEmoticon in _emoticonList) { int _tmpIterator = 0; // Create new item ChatbotEmoticons _emoticon = new ChatbotEmoticons(); // Create new list of frames _emoticon._frames = new List <Texture2D>(); // Store filename _emoticon._gifFile = _currentEmoticon + ".gif"; // Frame texture Texture2D _currentGifFrame = null; // Load all frames from resources while ((_currentGifFrame = Resources.Load("Chatbot/Unity Implementation/Emoticons/" + _currentEmoticon + "_" + _tmpIterator, typeof(Texture2D)) as Texture2D) != null) { // If we're running in the Unity editor #if UNITY_EDITOR // Set texture importer format SetTextureImporterFormat(_currentGifFrame); #endif // Store Texture _emoticon._frames.Add(_currentGifFrame); // Increase Iterator _tmpIterator++; } // Add to list _Emoticons.Add(_emoticon); // In Unity Editor and Unity version not 4.0.x #if (UNITY_EDITOR && !UNITY_4_0 && !UNITY_4_0_1) // Causes a freeze in Unity 4.0. Thus changes are first applied upon restart. // Save changed/new assets AssetDatabase.SaveAssets(); // Refresh database AssetDatabase.Refresh(); #endif } }
public void Equals_Object_ReturnsExpected(FrameDimension frameDimension, object obj, bool result) { Assert.Equal(result, frameDimension.Equals(obj)); }
private void BtnLoad_Click(object sender, EventArgs e) { Image img = new Bitmap(1, 1); string path = ""; bool flag = false; try { OpenFileDialog openFileDialog = new OpenFileDialog { Title = Language.DICT["MainTitle"], Filter = "All Support Image Formats|*.pcx;*.gif;*.bmp;*.png;*.jpg;*.jpeg;*.tiff|" + "PCX File|*.pcx|" + "GIF File|*.gif|" + "BMP File|*.bmp|" + "PNG File|*.png|" + "JPG File|*.jpg;*.jpeg|" + "TIFF File|*.tiff" }; if (openFileDialog.ShowDialog() == DialogResult.OK) { path = openFileDialog.FileName; string ext = path.Split('.').LastOrDefault().ToLower(); img = Image.FromFile(path); FrameDimension fd = new FrameDimension(img.FrameDimensionsList[0]); int framecount = img.GetFrameCount(fd); if (framecount > 1) { Misc.GifToIndex(img, Data); } else { Misc.GetIndexedItem(img, Data, 255, rdbModeMC.Checked ? 2 : rdbModeEF.Checked ? 1 : 0); } btnImport.Enabled = true; } else { btnImport.Enabled = false; } } catch (Exception ex) { try { img = Misc.DecodePCX(path); Misc.GetIndexedItem(img, Data, 255, rdbModeMC.Checked ? 2 : rdbModeEF.Checked ? 1 : 0); flag = true; btnImport.Enabled = true; } catch (Exception Ex) { MyMessageBox.Show(Language.DICT["MainTitle"], Language.DICT["MsgFatalImport"] + (flag ? Ex.Message : ex.Message)); btnImport.Enabled = false; return; } } PreviewBox.Image = img; lblPath.Text = Language.DICT["ImportlblPrefix"] + path; }
/// <summary> /// Merges multiple TIFF files (including multipage TIFFs) into a single multipage TIFF file. /// </summary> public static byte[] MergeTiff(params byte[][] tiffFiles) { byte[] tiffMerge = null; using (var msMerge = new MemoryStream()) { //get the codec for tiff files ImageCodecInfo ici = null; foreach (ImageCodecInfo i in ImageCodecInfo.GetImageEncoders()) { if (i.MimeType == "image/tiff") { ici = i; } } Encoder enc = Encoder.SaveFlag; EncoderParameters ep = new EncoderParameters(1); Bitmap pages = null; int frame = 0; foreach (var tiffFile in tiffFiles) { using (var imageStream = new MemoryStream(tiffFile)) { using (Image tiffImage = Image.FromStream(imageStream)) { foreach (Guid guid in tiffImage.FrameDimensionsList) { //create the frame dimension FrameDimension dimension = new FrameDimension(guid); //Gets the total number of frames in the .tiff file int noOfPages = tiffImage.GetFrameCount(dimension); for (int index = 0; index < noOfPages; index++) { FrameDimension currentFrame = new FrameDimension(guid); tiffImage.SelectActiveFrame(currentFrame, index); using (MemoryStream tempImg = new MemoryStream()) { tiffImage.Save(tempImg, ImageFormat.Tiff); { if (frame == 0) { //save the first frame pages = (Bitmap)Image.FromStream(tempImg); ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame); pages.Save(msMerge, ici, ep); } else { //save the intermediate frames ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage); pages.SaveAdd((Bitmap)Image.FromStream(tempImg), ep); } } frame++; } } } } } } if (frame > 0) { //flush and close. ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush); pages.SaveAdd(ep); } msMerge.Position = 0; tiffMerge = msMerge.ToArray(); } return(tiffMerge); }
/// <summary> /// 获取图片中的各帧 /// </summary> /// <param name="pPath">图片路径</param> /// <param name="pSavePath">保存路径</param> public void GetFrames(string pPath, string pSavedPath) { Image gif = Image.FromFile(pPath); FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]); int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧) for (int i = 0; i < count; i++) //以Jpeg格式保存各帧 { gif.SelectActiveFrame(fd, i); gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg); } }