【 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...
演示了为无线无人机电池充电设计的感应电力传输(IPT)系统 Dynamic Wireless Charging for (UAV) using Inductive Coupling 模拟了为无人机(UAV)量身定制的无线电力传输(WPT)系统。该模型演示了直流电到高频交流电的转换,通过磁共振在气隙中无线传输能量,以及整流回直流电用于电池充电。 系统拓扑包括: 输入级:使用IGBT/二极管开关连接到全桥逆变器的直流电压源(12V)。 开关控制:脉冲发生器以85 kHz(周期:1/85000秒)的开关频率运行,这是SAE J2954无线充电标准的标准频率。 耦合级:使用互感线性变压器块来模拟具有特定耦合系数的发射(Tx)接收(Rx)线圈。 补偿:包括串联RLC分支,用于模拟谐振补偿网络(将线圈调谐到谐振频率)。 输出级:桥式整流器(基于二极管),用于将高频交流电转换回直流电,以供负载使用。 仪器:使用示波器块进行全面的电压电流测量,用于分析输入/输出波形效率。 模拟详细信息: 求解器:离散Tustin/向后Euler(通过powergui)。 采样时间:50e-6秒。 4.主要特点 高频逆变:模拟85 kHz下IGBT的开关瞬态。 磁耦合:模拟无人机着陆垫机载接收器之间的松耦合行为。 Power GUI集成:用于专用电力系统离散仿真的设置。 波形分析:预配置的范围,用于查看逆变器输出电压、初级/次级电流整流直流电压。 5.安装与使用 确保您已安装MATLABSimulink。 所需工具箱:必须安装Simscape Electrical(以前称为SimPowerSystems)工具箱才能运行sps_lib块。 打开文件并运行模拟。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值