C# 转换函数 (Stream to Byte[],Byte to Image,Image to Byte[],Image缩放,Byte[] to Bitmap)

来源:互联网 发布:巡音露卡的事件簿知乎 编辑:程序博客网 时间:2024/05/17 21:56
1.Stream转byte[]
 publicbyte[]StreamToByteArr(Streamstream)
 {
  byte[]bytes=newbyte[stream.Length];//创建byte数组
   stream.Read(bytes, 0, bytes.Length);//将Stream读入byte数组
  stream.Seek(0,SeekOrigin.Begin);// 将流指向起始位置
   returnbytes;
 }

2. byte[]转Image
publicstaticImageGetImageByBytes(byte[]bytes)
{
 Imagephoto=null;
 using(MemoryStreamms=newMemoryStream(bytes))
  {
     ms.Write(bytes, 0, bytes.Length);
    photo=Image.FromStream(ms,true);
   }
   returnphoto;
}

3.Image转Byte[]
publicbyte[]GetByteImage(Imageimg)
{
 byte[]bt=null;
 if(!img.Equals(null))
  {
   using(MemoryStreammostream=newMemoryStream())
    {
     Bitmapbmp=newBitmap(img);
     bmp.Save(mostream,System.Drawing.Imaging.ImageFormat.Bmp);
     bt=newbyte[mostream.Length];
     mostream.Position= 0;
     mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
     }
  }
 returnbt;
}

4.Image图片缩放
publicImagepictureProcess(ImagesourceImage,inttargetWidth,inttargetHeight)
{
 intwidth;//图片最终的宽 
 intheight;//图片最终的高 
 try
  {
   System.Drawing.Imaging.ImageFormatformat=sourceImage.RawFormat;
   BitmaptargetPicture=newBitmap(targetWidth,targetHeight);
   Graphicsgraphics=Graphics.FromImage(targetPicture);
   graphics.Clear(Color.White);
   //计算缩放图片的大小 
   if(sourceImage.Width>targetWidth&&sourceImage.Height<=targetHeight)
    {
     width=targetWidth;
     height= (width*sourceImage.Height) / sourceImage.Width;
    }
   elseif(sourceImage.Width<=targetWidth&&sourceImage.Height>targetHeight)
    {
     height=targetHeight;
      width = (height*sourceImage.Width) / sourceImage.Height;
    }
    elseif(sourceImage.Width<=targetWidth&&sourceImage.Height<=targetHeight)
    {
     width=sourceImage.Width;
     height=sourceImage.Height;
    }
   else
    {
     width=targetWidth;
     height= (width*sourceImage.Height) / sourceImage.Width;
     if(height>targetHeight)
      {
       height=targetHeight;
       width= (height*sourceImage.Width) / sourceImage.Height;
       }
    }
    graphics.DrawImage(sourceImage, (targetWidth-width) / 2, (targetHeight-height) / 2,width,height);
    sourceImage.Dispose();
    returntargetPicture;
  }
 catch(Exceptionex)
  {
  }
  returnnull;
}

5.byte[] 转bitmap
 publicstaticBitmapBytesToBitmap(byte[]Bytes)
{
   MemoryStreamstream=null;
  try
   {
     stream=newMemoryStream(Bytes);
     returnnewBitmap((Image)newBitmap(stream));
    }
   catch(ArgumentNullExceptionex)
    {
       throwex;
    }
    catch(ArgumentExceptionex)
     {
        throwex;
     }
     finally
     {
        stream.Close();
      }
}
阅读全文
0 0