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

投稿

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

C#でUDPデータ受信

受信側サンプルコード // 基本 var receiveIpAddress = "127.0.0.1" ; var local = new IPEndPoint ( IPAddress . Parse ( receiveIpAddress ) , Port ) ; var remote = new IPEndPoint ( IPAddress . Any , 8006 ) as EndPoint ; socket . Bind ( local ) ; var buffer = new byte [ 3 ] ; while ( true ) { Console . WriteLine ( "Start Receiving" ) ; // var length = socket.ReceiveFrom(buffer, ref remote); var length = socket . Receive ( buffer ) ; var requiredBuffer = new byte [ length ] ; Buffer . BlockCopy ( buffer , 0 , requiredBuffer , 0 , length ) ; var data = Encoding . UTF8 . GetString ( requiredBuffer ) ; Console . WriteLine ( "data received: " + data ) ; } 受信側コードの注意点 bufferの配列サイズがdatagramサイズより小さいと、下記のようなエラーが出る System.Net.Sockets.SocketException (10040): A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datag

C#でenumに定義された値の一覧を取得する方法

下記のコードでenumに定義された値の一覧を取得できます。 // MyEnumの部分を一覧を取得したいenumに書き換えてください。 var enums = Enum . GetValues ( typeof ( MyEnum ) ) . Cast < MyEnum > ( ) ; // ループしてプリントしてみる。 foreach ( var @ enum in enums ) { Console . WriteLine ( @ enum . ToString ( ) ) ; } ちなみにコード内の「@」はC#の予約語を変数名で使えるようにするためのものです。 さらに下記のようGenericsを使って一般化したメソッドを定義できます。 public static IEnumerable < T > IterateEnum < T > ( ) where T : Enum = > Enum . GetValues ( typeof ( T ) ) . Cast < T > ( ) ;

C#のClassとStruct

C#のClassとStructの性能や使い分けについてメモ。 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct https://medium.com/@mdfarragher/whats-faster-in-c-a-struct-or-a-class-99e4761a7b76 https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct?redirectedfrom=MSDN

C#でMarshalクラスを使ってbyte配列から構造体を生成する方法

C#の通信プログラムでbyte配列を読み込んで、構造体(struct)を生成したいときにサンプルコードの紹介です。 Genericsを使って任意の構造体をbyte配列から生成できるようにしています。 public static T ReadAsStruct < T > ( this byte [ ] bytes , int startIndex ) where T : struct { // GCHandle.Allocクラスを使ってメモリ上のデータがガーベッジコレクタの対象にならないようにする。 var handle = GCHandle . Alloc ( bytes , GCHandleType . Pinned ) ; try { // Marshalクラスのメソッドを使って、byte配列のIntPtr(ポインタ)を取得。 var ptr = Marshal . UnsafeAddrOfPinnedArrayElement ( bytes , startIndex ) ; // IntPtrで指定した位置のbyte配列から構造体を生成。 return ( T ) Marshal . PtrToStructure ( ptr , typeof ( T ) ) ; } finally { // 重要!!必ずGCHandleを開放して、再びbyte配列がガーベッジコレクタの対象になるようにする。 handle . Free ( ) ; } } ちょっと考察 ■ パフォーマンス 毎回GCHandle.Alloc, Freeを行う分、パフォーマンスのオーバーヘッドが発生します。パフォーマンスが気になる場合は、GCHandle.Alloc, Freeの間に、複数の構造体を生成するようにするとよいかもしれません。 ■ 他の書き方 startIndexがいつもゼロの場合、下記の部分は、 var ptr = Marshal . UnsafeAddrOfPinnedArrayElem

C#でbyte orderを反転する方法

UDPパケットの受信時に受信したデータのbyte orderを反転する必要がある場合があります。そんな場合に使えるbyte orderを反転するC#のコードの紹介です。 処理の流れは下記になります。 BitConverter.GetBytesメソッドを使って、値のbyte配列表現を取得。 Array.Reverseメソッドでbyte配列の順番を反転する。 BitConverter.ToXXXメソッドで元の値の型に戻す。 ushort, uint, int, ulong, float, doubleなどの型についてコードを示します。 public static void ReverseBytes ( this ref ushort value ) { var source = BitConverter . GetBytes ( value ) ; Array . Reverse ( source ) ; value = BitConverter . ToUInt16 ( source , 0 ) ; } public static void ReverseBytes ( this ref uint value ) { var source = BitConverter . GetBytes ( value ) ; Array . Reverse ( source ) ; value = BitConverter . ToUInt32 ( source , 0 ) ; } public static void ReverseBytes ( this ref int value ) { var source = BitConverter . GetBytes ( value ) ; Array . Reverse ( source ) ; value = BitConverter . ToInt32 ( source , 0 ) ; } public static void ReverseBytes ( this ref ulong value ) { v

C#: Read Image Metadata Using BitmapMetadata Class

Introduction In this post, I will demonstrate how to read image metadata using BitmapMetadata class in C#. Before staring explanation, we should notice there are two namespaces that can handle image in C#. System.Drawing namespace: I tested in this post System.Windows.Media.Imaging In this post, we will use classes under System.Windows.Media.Imaging. Code for Reading Image Metadata Actually code itself is quite simple :) Please see code below. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Media.Imaging; using System.Diagnostics; namespace MetadataExample { public static class ReadImageMetadataExample { public static void a(string fileName) { var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); var img = BitmapFrame.Create(fs); var metadata = img.Metadata as BitmapMetadata; Debug.WriteLine("=== metadata ===

C#: How to Read Image MetaData from System.Drawing.Imaging.PropertyItem

I have written simple debug code for printing out PropertyItems in System.Drawing.Image object. The key part of the code: mapping between Id property of PropertyItem and description of associated to the property item. decode PropertyItem value (byte array) to human readable format string The code itself will be shown at the bottom of this post. Below is a sample image which will be passed to the program and the corresponding output generated by the program. Property Item 1 Id: 0x10e Type: 2 Length: 17 bytes Type String: ASCII Descriotion: PropertyTagImageDescription Value : MetaData Example Property Item 2 Id: 0x131 Type: 2 Length: 7 bytes Type String: ASCII Descriotion: PropertyTagSoftwareUsed Value : Picasa Property Item 3 Id: 0x9000 Type: 7 Length: 4 bytes Type String: Undefined Descriotion: PropertyTagExifVer Value : Property Item 4 Id: 0xa002 Type: 4 Length: 4 bytes Type String: Long (3

C#: Extract Gif Frame Images From an Animated Gif Image

I wrote the post for extracting gif frame image from an animated gif image in Java - Java: Extract Gif Images From An Animated Gif Image . In this post, I have tried to do same thing in C# as well :D Code using System.Drawing; using System.Drawing.Imaging; namespace Utility { public class GifImageUtils { public static void SaveAnimatedGifFrames(string path, string outDir) { var gifImg = Image.FromFile(path); var dimension = new FrameDimension(gifImg.FrameDimensionsList[0]); int frameCount = gifImg.GetFrameCount(dimension); for (int i = 0; i < frameCount; i++) { gifImg.SelectActiveFrame(dimension, i); // create a frame image from the original source image - clone is mandatory var frame = (Image)gifImg.Clone(); frame.Save(outDir+"/"+i+".gif", ImageFormat.Gif); } } } } Exa

C#: Create Indexed PNG Using System.Windows.Media.BitmapSource with Pre-defined Palettes in BitmapPalettes Class

Creating Indexed PNG in C# In C#, there are mainly two namespaces to creating image... System.Drawing namespace System.Windows.Media namespace I've already written the post for creating indexed png using System.Drawing namespace classes - Create Indexed PNG Using C# .Net . So, in this post, I will show you how to create indexed png using classes under System.Windows.Media namespace. Preparation for Using Classes Under System.Windows.Media You need to add following dlls to your project reference in order to handle images using classes under System.Windows.Media. PresentationCore.dll Xaml.dll WindowsBase.dll Creating Palette Based Indexed Image If you would like to create indexed png, first of all, you should create color palette which can hold max 256 colors. Creating color palette is trivial. Please see the below example code: var colors = new List<Color>(); colors.Add(Color.FromRgb(255, 0, 0)); // 0 - red colors.Add(Color.FromRgb(0, 255, 0)); // 1 -

C#: Create Indexed PNG Image Using pngcs Library

I have written C# program which create an indexed packed png image from a given png image using pngcs 1_1_4. What you need to use pngcs is adding reference of dll to your Visual Studio project - Pngcs.dll and ICSharpCode.SharpZipLib.dll for .Net 2.0, and Pngcs45.dll for .Net4.5. I have used .Net 2.0 version because my Visual Studio is 2010. I have already written a program for generating indexed png in C# on this post - Create Indexed PNG Using C# .Net . But the png encoder Microsoft officially provides does not support compression level parameter. That is, even if png is indexed, the size of png image is not sufficient for me :( So I investigated other library which can handle png in C#, and finally found pncs! Main features of my program: Use minimum bit per pixel as much as possible Image which has alpha channel is is not supported because pngcs library doesn't support color palette with alpha channel If given image has alpha channel but all alpha channel value is 25