スキップしてメイン コンテンツに移動

投稿

ラベル(C#)が付いた投稿を表示しています

Create Indexed PNG Using C# .Net

Currently I am working on optimizing image size. In this post, I will demonstrate the C# code for creating indexed png image. The code might not be perfect yet, but hope this code will give you some hints ;) A few things I am struggling with while I am writing the example code: Palette: you should take ColorPalette from Bitmap, modify the ColorPalette object and set buck it to the Bitmap object. BitmapData.Stride is often bigger than BitmapData.Width. You should be careful to check both values difference when you manipulating the image array index. The example code uses classes in System.Drawing namespace. But looks there is another option to manipulate image in C# .Net - System.Windows.Media namespace. C# Source Code for Creating Indexed PNG The following implementation of CreateIndexedPng method is able to take only non-indexed image like Format24bppRgb or Format32bppArgb. (I might add other image formats in future.) If the source image has only 2 colors, we can use For

C#: Convert 1 Dimensional Array to Fixed Size 2 Dimensional Array

Code using System; using System.Collections.Generic; using System.Linq; namespace Utility { public static class ArrayUtils { public static T[,] To2DimensionalArray (this T[] source, int block){ var ret = new T[block, source.Length/block]; for (int i = 0, offset = 0, len = ret.Length; offset < len; i++, offset = i * block) { for(int j = 0; j < block; j++){ ret[j, i] = source[offset + j]; } } return ret; } } } Example Usage int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; int[,] array2 = array1.To2DimensionalArray(3); /* array2 will be... { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } */

C#: Convert 1 Dimensional Array to 2 Dimensional Jagged Array

Code using System; using System.Collections.Generic; using System.Linq; namespace Utility { public static class ArrayUtils { public static T[][] To2DimensionalJaggedArray<T>(this T[] source, int block) { var res = new T[block][]; int size = source.Length / block; for (int i = 0; i < block; i++) { res[i] = new T[size]; Array.Copy(source, i*size, res, 0, size); // advantage of jagged array is that you can use Array.copy method etc. } return res; } } } Example Usage int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; int[][] array2 = array1.To2DimensionalJaggedArray(3); /* array2 will be int[3][] and each elements will be... [0] = { 1, 2, 3 }, [1] = { 4, 5, 6 }, [2] = { 7, 8, 9 } */

Create Web Page Thumbnail by Java or C#

I have googled how to create web page thumbnail. Hope this post helps anyone who are trying to create web page image. Java Lunch a native browser from Desktop class and capture active window by Robot class I think this isn't smart way however it should work. Please read this . The disadvantage of this method is you cannot achieve it on off screen. Using SWT Browser Please read this . The biggest disadvantage is again you cannot do it on off screen. Pure Java Solution If you are seeking pure java solution, maybe Cobra or Css Box will help you. Unfortunately Cobra is not updated recently, and Css Box is still very new on the other hand. I hope I can post example of code on this blog in near future.... Using QT-Jambi I'm not familiar with Qt library but this post explains how to create web page image by Qt Jambi , which is java wrapper of Qt Library. The post provides code example, too!! C# Using System.Windows.Forms.WebBrowser this article in www.codeproj

C#: How to Read Image as Double Array (for Image Processing)

As you know I am really interested in image processing. For my first step, I wrote the program for reading image as double array in C#. The code is imperfect but I think this will help someone's understand.... Here is an example usage. var original = Bitmap.FromFile(@"C:\temp\test.jpg"); double[,] values = new Bitmap(original).To2DimDoubleArray(); // image processing part! // let's do something fun :D - filtering, binalizing, etc. // for now, removing R value from the image. for (int i = 0, len = values.Length/values.GetLength(0); i < len; i++ ) { //values[0, i] = 0; // a values[1, i] = 0; // r //values[2, i] = 0; // g //values[3, i] = 0; // b } values .ToBitmap(original.Width, original.Height, PixelFormat.Format32bppArgb) .SaveImageAsJpeg(@"c:\temp\test2.jpg", 75); The image processing result of above example program. The left image is original, the right image is the result image which is red value is removed.

C# Dictionary which Returns Default Value if Key is Missing

I have written Dictionary which returns default value if the key is missing in the dictionary. You simply pass lambda function for returning value when the key is missing in Dictionary to its constructor. using System; using System.Collections.Generic; namespace Utility.Data { public class DefaultDictionary<TKey, TValue> : Dictionary<TKey, TValue> { private readonly Func<TKey, TValue> defaulter; public DefaultDictionary(Func<TKey, TValue> defaulter) { this.defaulter = defaulter; } public TValue GetDefaultValueIfMissing(TKey key){ if (ContainsKey(key)) { return this[key]; } return defaulter(key); } } } This is how to use.... var dict = new DefaultDictionary<string, IList<string>>((key) => new List<string>()); // should return empty list var list = dict.GetDefaultValueIfMissing("key1&

C#: Reflection Tips

C# is a very powerful language. However for this "powerful" perspective, there are various way to achieve something and you might hover among which way to take (at least for me :D). In this post I will focus on "Reflection" and introduce some small code spinets. First we assume this trivial class is defined in Utility assembly. namespace Utility.Sample { public class Target { public string wrapByDoubleQuote(string text) { return "\"" + text + "\""; } } } Get Type from String and Instantiate by Activator // type from reflection Type type = Type.GetType("Utility.Sample.Target"); // instantiate object from Type Target target = Activator.CreateInstance(type) as Target; // invoke method normally Console.WriteLine(target.wrapByDoubleQuote("contents")); Instantiate Object from ConstructorInfo and Invoke Method by Reflection // type from reflectio

C#: Download All Image Links from Html Page

I know this is not perfect way. But I would like to give hints to anyone who would like to download all links in html page. Example usage is something like this. // only download "jpg" files HttpUtils.SaveFirstLevelLinksToFile("", Encoding.UTF8, "c:/temp/", link => link => ".jpg".Equals(Path.GetExtension(link.Link), StringComparison.OrdinalIgnoreCase) ); Main code is below. // main entry point method public static void SaveFirstLevelLinksToFile(string baseUri, Encoding enc, string dir, Func<LinkAttr, bool> filter) { ProcessAllExtractedLinksInHtmlText(GetPage(baseUri, enc), link => { try { if (!filter(link)) return; Uri uri = ConvertToAbsoluteURL(baseUri, link.Link); var filePath = dir + uri.AbsoluteUri.GetFileName().Replace("?", ""); uri.AbsoluteUri.GetAndSaveToFile(filePath);

C#: Capture Screen

Here is the code for capturing current screen in given Rectangle region. public static Bitmap CaptureFromScreen(Rectangle rc) { var bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb); using (var g = Graphics.FromImage(bmp)) { g.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy); } return bmp; } You can give something like below as a Rectangle argument // full screen area Screen.PrimaryScreen.Bounds; // 640 x 480 rectamgle from left side corner new Rectangle(0, 0, 640, 480); // working area Screen.PrimaryScreen.WorkingArea; The following links are helpful. http://homepage1.nifty.com/yasunari/VB/VB2005/DrawToScreen.htm : Sorry this page is written in Japanese... http://www.bobpowell.net/capture.htm http://msdn.microsoft.com/en-us/library/dd144871(VS.85).aspx http://msdn.microsoft.com/en-us/library/dd162920(VS.85).aspx

C#: Extract A Href Links from Html Text

// I know 1, 2, 3 is bad grouping name X( private readonly static Regex LINK_REGEX = new Regex( @"<a\s+[^>]*href\s*=\s*(?:(?<3>'|"")(?<1>[^\3>]*?)\3|(?<1>[^\s>]+))[^>]*>(?<2>.*?)</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled ); public static void ExtractLinks(string text, ICollection<string> links) { LINK_REGEX.ApplyAllMatched(text, (m) => links.Add(m.Groups[1].Value)); } Helper method which processes matched string for each. public static void ApplyAllMatched(this Regex regex, string text, Action apply) { for (var m = regex.Match(text); m.Success; ) { apply(m); m = m.NextMatch(); } }

C#: Save Image as JPEG or PNG format

Just a simple code tips for saving image as JPEG or PNG format in C#. Save image as JPEG with Quality parameter public static readonly ImageCodecInfo JPEG_CODEC = GetEncoderInfo("image/jpeg"); public static void SaveImageAsJpeg(this Image src, string fileName, int quality) { var eps = new EncoderParameters(1); var ep = new EncoderParameter(Encoder.Quality, quality); eps.Param[0] = ep; src.Save(fileName.ChangeExtension("jpg"), JPEG_CODEC, eps); } public static ImageCodecInfo GetEncoderInfo(string mineType) { return ImageCodecInfo.GetImageEncoders().First(enc => enc.MimeType == mineType); } Save image as PNG public static void SaveImageAsPng(this Image src, string fileName) { src.Save(fileName.ChangeExtension("png"), ImageFormat.Png); }

C#: Resize Image

// Default parameters are almost the highest quality setting. public static Bitmap Resize(this Image src, int w, int h, SmoothingMode smoothingMode = SmoothingMode.AntiAlias, InterpolationMode interpolationMode = InterpolationMode.HighQualityBicubic, PixelOffsetMode pixelOffsetMode = PixelOffsetMode.HighQuality) { var newImage = new Bitmap(w, h); using (var gr = Graphics.FromImage(newImage)) { gr.SmoothingMode = smoothingMode; gr.InterpolationMode = interpolationMode; gr.PixelOffsetMode = pixelOffsetMode; gr.DrawImage(src, 0, 0, w, h); } return newImage; } // resize image based on given percentage public static Bitmap ResizedByPercentage(this Image src, double percent) { var rW = (int)Math.Round(src.Width * percent, 0); var rH = (int)Math.Round(src.Height * percent, 0); return src.Resize(rW, rH); } // resize image limited in given w, h parameter public static Bitmap ResizeImageIn(this Image src, int w, i

C#: Extract Charset from Html Meta Tag

private static readonly Regex META_TAG_CHARSET_REGEX = new Regex(@"<META\s+http-equiv\s*=\s*Content-Type\s+content=\s*""[^""]*\s+charset\s*=\s*(?<charset>[^""\s]*).*""\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static string ExtractCharset(string htmlText) { string result = null; var m = META_TAG_CHARSET_REGEX.Match(htmlText); if (m.Success) { result = m.Groups["charset"].Value; } return result; } Note: System.Text.RegularExpressions.Regex class is thread safe according to this msdn doc .

C#: XPath and HtmlTextWriter Example

Hey guys!! This post show you how to use XPath in C#. I wrote program for formatting rss feed (xml) to html for its example. XPath in C# The simplest way is just creating XmlDocument and call SelectNodes method. var xmlString = "some xml string...." // create XmlDocment var doc = new XmlDocument(); doc.LoadXml(xmlString); // selecting nodes by xpath string doc.SelectNodes("/rss/channel/item"); RSS Xml to Html Example Okay here is a simple XPath example - converting rss xml to html. using System.IO; using System.Web.UI; using System.Web; namespace Utility { public class RSStoHtmlWriter : HTMLWriteHelper { private readonly string url; public RSStoHtmlWriter(string url) { this.url = url; } public override void WriteBody(HtmlTextWriter htmlWriter) { using (var reader = new XmlTextReader(url)) { // **** using XPath!! **** // As you n

C#: Generate Integer Sequence

This is quick tips. If you would like to generate sequence in C#, you can do like below: // generate 1, 2, 3,...., 24 foreach (var i in Enumerable.Range(1, 25)){ // do somthing nice :D } In my opinion, C# (.Net implementation) has nicer built-in libraries and syntax than Java...

C#: XML string to XmlDocument

I have wrote some utility methods for creating XmlDocument from XML string. public static class XMLUtils { // xml string to XmlDocument public static XmlDocument ToXmlDocument(this string xml) { var doc = new XmlDocument(); doc.LoadXml(xml); return doc; } // XmlReader to XmlDocument // XMLReader is useful for read xml data from url source public static XmlDocument ToXmlDocument(this XmlReader reader) { var doc = new XmlDocument(); doc.Load(reader); return doc; } // path to xml file to XmlDocument public static XmlDocument ReadFromPath( string path) { return ToXmlDocument(File.ReadAllText(path)); } }