【 Silverlight】Bitmap 位图和Particle引擎


毋庸置疑又是繁忙的一年过去了,在这一年中我的项目BLUR BLUR BLUR以致于我到现在才有时间发表一篇新的BLOG,不过放心,十年不鸣,一鸣惊人。我带给你的总是业界最新的技术

首先也是首要的我们今天要讨论流数据和颗粒,下面是部分的代码:

注意: 上传任何的24位位图所有的二进制流都在客户端处理,所以服务端不需要任何的处理



这里的主循环用来从客户端的对话框中取出一个位图,然后将其解重要信息解析到客户端的一个数组,然后保存那些重要的图像颜色信息

   [...]
   
using System.Windows.Media.Imaging;
   
using System.IO;
   
using System.Windows.Browser;
   
using System.Windows.Resources;

   drawSqaure[] tiles;     
   
double totalCol = 0;
   
double totalRow = 0;
   
double imageWidth = 0;
   
double imageHeight = 0;

   [...]
   
   
private void OpenBMP()
   
{
       OpenFileDialog ofd 
= new OpenFileDialog();

       
if (ofd.ShowDialog() == DialogResult.OK)
       
{
           Stream stream 
= ofd.SelectedFile.OpenRead();
           output 
= ofd.SelectedFile.Name;

        
       
// Find out how big the file is. Create a Byte array to hold it.
       
// Read the values you need from the Bitmap data stream...
    
           
int nBytes = Convert.ToInt32(stream.Length);
           
byte[] ByteArray = new byte[nBytes];
           
int nBytesRead = stream.Read(ByteArray, 0, nBytes);
           stream.Close();

    
       
// BMP Header files start with B and M in Ascii
//
通过文件头的信息来判断文件的类型
                      
           
if ((ByteArray[0== 66&& (ByteArray[1== 77))
           
{
               output 
+= " [24bit BMP File] ";
           }

           
else
           
{
               output 
= " ERROR: File is not a BMP";
               txtOut.Text 
= output;
               
return;
           }

       
       
// BMP files will pad the stream with leading zeros if the
       
// image width in pixels is not divisble by 4
         
           imageWidth 
= (double)(convert4Bytes(ByteArray[18], ByteArray[19], 
            ByteArray[
20], ByteArray[21]));
           
double rowPad = imageWidth % 4;
           imageHeight 
= (double)(convert4Bytes(ByteArray[22], ByteArray[23], 
            ByteArray[
24], ByteArray[25]));
           
int dataOffset = convert4Bytes(ByteArray[10], ByteArray[11], 
            ByteArray[
12], ByteArray[13]);
           
int bitDepth = convert2Bytes(ByteArray[28], ByteArray[29]);
           
int imageDataSize = convert4Bytes(ByteArray[34], ByteArray[35], 
            ByteArray[
36], ByteArray[37]);

           
if ( (imageWidth > 600|| (imageHeight > 600) ) {
               output 
= "ERROR: Image too large. Please select another file.";
               txtOut.Text 
= output;
               
return;
           }


           
if (bitDepth != 24)
           
{
               output 
+= "ERROR: Color depth must be set at 24 bits.";
               txtOut.Text 
= output;
               
return;
           }


       
    
// I will be calculating out the color average of 10x10 pixel 
    
// squares from the image and storing them in a drawSqaure object.
    
// A 24bit BMP uses 3 bytes per pixel for the color. This code 
    
// can easily be expanded to support other bit depths as well.
    
           
int resolution = 10;
           
int bytesPerPixel = 3;

           totalCol 
= Math.Floor( imageWidth / resolution);
           totalRow 
= Math.Floor( imageHeight / resolution);

           
int totalTiles = (int)(totalCol * totalRow);
           tiles 
= new drawSqaure[totalTiles];
                        
           
double rowOffset = 0;
           
double pointer = 0;
           
int index = 0;

       
    
// Here is the important part. I have now stored the Bitmap 
    
// image's stream in my byte array and I have created an array 
    
// of 'drawSquare' objects to be populated with the average
    
// of the 10 x 10 pixel square color values I will next calculate.
       

            
for (int r = 0; r < totalRow; r++)
            
{
        
    
// BMP files send their pixel data from the bottom left corner
    
// of the image UP. Also, while their pixel data is traditional 
    
// 0-255 per RGB color, the ORDER is reversed, so it comes in 
    
// BGR, not RGB.
        
            rowOffset 
= 54 + (r*(resolution * 
            ((imageWidth 
* bytesPerPixel) + rowPad) ));
            
for (int c = 0; c < totalCol; c++)
            
{
            pointer 
= rowOffset + (c * resolution * bytesPerPixel);
            drawSqaure d 
= new drawSqaure();
            
int b = 0;
            
int g = 0;
            
int red = 0;
                        
            
for (int i = 0; i < resolution; i++)
            
{
              
for (int y = 0; y < resolution; y++)
              
{
                 
int calc = Convert.ToInt32(pointer + 
            (i
*((imageWidth*bytesPerPixel)+rowPad)) + (y*3));
                 b 
+= (int)ByteArray[calc];
                 g 
+= (int)ByteArray[calc+1];
                 red 
+= (int )ByteArray[calc + 2];
              }

            }

        
    
// Since the above nested for loops will sample a 10 x 10 pixel   
        
// square, I need to divide the sum of each Color by 100 to 
        
// get its color average per channel.
          
            d.red 
= red / 100;
            d.blue 
= b / 100;
            d.green 
= g / 100;
            tiles[index] 
= d;
            index
++;
          }

      }

      txtOut.Text 
= output;
      ByteArray 
= null;
      buildUI();
    }

}


drawSquare 对象保存的是每个画布TILE将添加到屏幕的颜色的平均值:
    public class drawSqaure
    
{
        
public int red getset; }
        
public int blue getset; }
        
public int green getset; }

    }


下面是一个创建UI的主循环

   private void buildUI()
   
{
     
int index = 0;
     
int nodeSize = 2;
     nodes.Children.Clear();

     
for (int r = 0; r < totalRow; r++)
     
{
       
for (int c = 0; c < totalCol; c++)
        
{
          node n 
= new node();
          n.SetValue(NameProperty, 
"n_" + c.ToString() + "_" + r.ToString());
          n.X 
= origin.X - (totalCol*(nodeSize*.5)) + (c * nodeSize);
          n.Y 
=  origin.Y - 30 + (totalRow*(nodeSize*.5)) - (r * nodeSize);
          n.anchor 
= new Point(n.X, n.Y);
          n.vX 
= 0;
          n.vY 
= 0;
          drawSqaure d 
= tiles[index];
          index
++;
          n.setColor(Color.FromArgb(
0xFF, Convert.ToByte(d.red), 
        Convert.ToByte(d.green), Convert.ToByte(d.blue))); 
          nodes.Children.Add(n);
        }

      }


      index 
= 0;
      tiles 
= null;
   }


        
private Int32 convert4Bytes(byte a, byte b, byte c, byte d) 
    
return ( (d<<24| (c<<16| (b<<8| (a)); }

        
private Int32 convert2Bytes(byte a, byte b)
    
return ((b << 8| (a)); }


用户控制节点是空的,我们可以通过setColor()设置2×2的矩形的颜色,或者通过X,Y属性,正如我前面无数次提到的那样

最后的动画看起来就是这样的:

 
       void sb_Completed(object sender, EventArgs e)
        
{
            
foreach (node n in nodes.Children)
            
{
                n.vX 
+= ((double)r.Next(100- 50.0)/ 5.0;
                n.vY 
+= ((double)r.Next(100- 50.0/ 5.0;
                n.vX 
*= buzz;
                n.vY 
*= buzz;
                n.X 
+= n.vX;
                n.Y 
+= n.vY;
                n.X 
+= (n.anchor.X - n.X) * .07;
                n.Y 
+= (n.anchor.Y - n.Y) * .07;
            }


            sb.Begin();
        }


当然在我的例子里我添加了很多的树枝啊铃铛啊什么的,来控制滚动条中的BUZZ变量的位置扽等,但是上面的俄代码对于要使例子能够跑起来却是必要的







Needless to say, its been one hectic year so far! Between Project Maestro at SXSW, Teaching at MIX08, Winning the PhizzPop nationals, Artists in Residency and getting ready for the Web 2.0 Expo, this is the first chance I've had to push up a new post! But this is a great time for Silverlight development and I'll be keeping you updated with some amazing things just over the horizon!


First things first, we're going to talk about Streaming data and particles today. Here's the project the code snippet comes from:

Instructions: Move the slider to increase the particle buzz. Upload any 24 bit .BMP file. All binary streams are processed client side, there is no server manipulation required.



Here is the main loop that takes the BMP file from a client side dialog box, parses it on the client side to extract the important informatio, and populate an array of custom color objects that will be used to draw the tiles:

   [...]
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Browser;
using System.Windows.Resources;

drawSqaure[] tiles;
double totalCol = 0;
double totalRow = 0;
double imageWidth = 0;
double imageHeight = 0;

[...]

private void OpenBMP()
{
OpenFileDialog ofd = new OpenFileDialog();

if (ofd.ShowDialog() == DialogResult.OK)
{
Stream stream = ofd.SelectedFile.OpenRead();
output = ofd.SelectedFile.Name;


// Find out how big the file is. Create a Byte array to hold it.
// Read the values you need from the Bitmap data stream...

int nBytes = Convert.ToInt32(stream.Length);
byte[] ByteArray = new byte[nBytes];
int nBytesRead = stream.Read(ByteArray, 0, nBytes);
stream.Close();


// BMP Header files start with B and M in Ascii

if ((ByteArray[0] == 66) && (ByteArray[1] == 77))
{
output += " [24bit BMP File] ";
}
else
{
output = " ERROR: File is not a BMP";
txtOut.Text = output;
return;
}

// BMP files will pad the stream with leading zeros if the
// image width in pixels is not divisble by 4

imageWidth = (double)(convert4Bytes(ByteArray[18], ByteArray[19],
ByteArray[20], ByteArray[21]));
double rowPad = imageWidth % 4;
imageHeight = (double)(convert4Bytes(ByteArray[22], ByteArray[23],
ByteArray[24], ByteArray[25]));
int dataOffset = convert4Bytes(ByteArray[10], ByteArray[11],
ByteArray[12], ByteArray[13]);
int bitDepth = convert2Bytes(ByteArray[28], ByteArray[29]);
int imageDataSize = convert4Bytes(ByteArray[34], ByteArray[35],
ByteArray[36], ByteArray[37]);

if ( (imageWidth > 600) || (imageHeight > 600) ) {
output = "ERROR: Image too large. Please select another file.";
txtOut.Text = output;
return;
}

if (bitDepth != 24)
{
output += "ERROR: Color depth must be set at 24 bits.";
txtOut.Text = output;
return;
}


// I will be calculating out the color average of 10x10 pixel
// squares from the image and storing them in a drawSqaure object.
// A 24bit BMP uses 3 bytes per pixel for the color. This code
// can easily be expanded to support other bit depths as well.

int resolution = 10;
int bytesPerPixel = 3;

totalCol = Math.Floor( imageWidth / resolution);
totalRow = Math.Floor( imageHeight / resolution);

int totalTiles = (int)(totalCol * totalRow);
tiles = new drawSqaure[totalTiles];

double rowOffset = 0;
double pointer = 0;
int index = 0;


// Here is the important part. I have now stored the Bitmap
// image's stream in my byte array and I have created an array
// of 'drawSquare' objects to be populated with the average
// of the 10 x 10 pixel square color values I will next calculate.


for (int r = 0; r < totalRow; r++)
{

// BMP files send their pixel data from the bottom left corner
// of the image UP. Also, while their pixel data is traditional
// 0-255 per RGB color, the ORDER is reversed, so it comes in
// BGR, not RGB.

rowOffset = 54 + (r*(resolution *
((imageWidth * bytesPerPixel) + rowPad) ));
for (int c = 0; c < totalCol; c++)
{
pointer = rowOffset + (c * resolution * bytesPerPixel);
drawSqaure d = new drawSqaure();
int b = 0;
int g = 0;
int red = 0;

for (int i = 0; i < resolution; i++)
{
for (int y = 0; y < resolution; y++)
{
int calc = Convert.ToInt32(pointer +
(i*((imageWidth*bytesPerPixel)+rowPad)) + (y*3));
b += (int)ByteArray[calc];
g += (int)ByteArray[calc+1];
red += (int )ByteArray[calc + 2];
}
}

// Since the above nested for loops will sample a 10 x 10 pixel
// square, I need to divide the sum of each Color by 100 to
// get its color average per channel.

d.red = red / 100;
d.blue = b / 100;
d.green = g / 100;
tiles[index] = d;
index++;
}
}
txtOut.Text = output;
ByteArray = null;
buildUI();
}
}


The drawSquare object simply holds the averaged color values per canvas tile we will add to the screen:

    public class drawSqaure
{
public int red { get; set; }
public int blue { get; set; }
public int green { get; set; }

}


And here is what the buildUI() loop looks like:

   private void buildUI()
{
int index = 0;
int nodeSize = 2;
nodes.Children.Clear();

for (int r = 0; r < totalRow; r++)
{
for (int c = 0; c < totalCol; c++)
{
node n = new node();
n.SetValue(NameProperty, "n_" + c.ToString() + "_" + r.ToString());
n.X = origin.X - (totalCol*(nodeSize*.5)) + (c * nodeSize);
n.Y = origin.Y - 30 + (totalRow*(nodeSize*.5)) - (r * nodeSize);
n.anchor = new Point(n.X, n.Y);
n.vX = 0;
n.vY = 0;
drawSqaure d = tiles[index];
index++;
n.setColor(Color.FromArgb(0xFF, Convert.ToByte(d.red),
Convert.ToByte(d.green), Convert.ToByte(d.blue)));
nodes.Children.Add(n);
}
}

index = 0;
tiles = null;
}

private Int32 convert4Bytes(byte a, byte b, byte c, byte d)
{ return ( (d<<24) | (c<<16) | (b<<8) | (a)); }

private Int32 convert2Bytes(byte a, byte b)
{ return ((b << 8) | (a)); }



The node user control is empty except for a 2x2 rectangle that we can change the fill with through its setColor() function as well as the X and Y public properties that I've gone over many times before.

Finally, the animation engine looks something like this:

        void sb_Completed(object sender, EventArgs e)
{
foreach (node n in nodes.Children)
{
n.vX += ((double)r.Next(100) - 50.0)/ 5.0;
n.vY += ((double)r.Next(100) - 50.0) / 5.0;
n.vX *= buzz;
n.vY *= buzz;
n.X += n.vX;
n.Y += n.vY;
n.X += (n.anchor.X - n.X) * .07;
n.Y += (n.anchor.Y - n.Y) * .07;
}

sb.Begin();
}
Of course, I added a couple more bells and whistles in mine, such as controlling the value of the buzz variables above by the position of the slider, but I'll leave you to customize your project anyway you want. The above outlines the essentials required to get it up and running.

Hope you like it. Drop me a note if you do anything cool with this...
基于可靠性评估序贯蒙特卡洛模拟法的配电网可靠性评估研究(Matlab代码实现)内容概要:本文围绕“基于可靠性评估序贯蒙特卡洛模拟法的配电网可靠性评估研究”,介绍了利用Matlab代码实现配电网可靠性的仿真分析方法。重点采用序贯蒙特卡洛模拟法对配电网进行长时间段的状态抽样与统计,通过模拟系统元件的故障与修复过程,评估配电网的关键可靠性指标,如系统停电频率、停电持续时间、负荷点可靠性等。该方法能够有效处理复杂网络结构与设备时序特性,提升评估精度,适用于含分布式电源、电动汽车等新型负荷接入的现代配电网。文中提供了完整的Matlab实现代码与案例分析,便于复现扩展应用。; 适合人群:具备电力系统基础知识Matlab编程能力的高校研究生、科研人员及电力行业技术人员,尤其适合从事配电网规划、运行与可靠性分析相关工作的人员; 使用场景及目标:①掌握序贯蒙特卡洛模拟法在电力系统可靠性评估中的基本原理与实现流程;②学习如何通过Matlab构建配电网仿真模型并进行状态转移模拟;③应用于含新能源接入的复杂配电网可靠性定量评估与优化设计; 阅读建议:建议结合文中提供的Matlab代码逐段调试运行,理解状态抽样、故障判断、修复逻辑及指标统计的具体实现方式,同时可扩展至不同网络结构或加入更多不确定性因素进行深化研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值