1.Stream转byte[]
public
byte
[]
StreamToByte
Arr(
Stream
stream
)
{
byte
[]
bytes
=
new
byte
[
stream
.
Length
]; //创建byte数组
stream
.
Read
(
bytes
, 0,
bytes
.
Length
); //将Stream读入byte数组
stream
.
Seek
(0,
SeekOrigin
.
Begin
);// 将流指向起始位置
return
bytes
;
}
2. byte[]转Image
public
static
Image
GetImageByBytes
(
byte
[]
bytes
)
{
Image
photo
=
null
;
using
(
MemoryStream
ms
=
new
MemoryStream
(
bytes
))
{
ms
.
Write
(
bytes
, 0,
bytes
.
Length
);
photo
=
Image
.
FromStream
(
ms
,
true
);
}
return
photo
;
}
3.Image转Byte[]
public
byte
[]
GetByteImage
(
Image
img
)
{
byte
[]
bt
=
null
;
if
(!
img
.
Equals
(
null
))
{
using
(
MemoryStream
mostream
=
new
MemoryStream
())
{
Bitmap
bmp
=
new
Bitmap
(
img
);
bmp
.
Save
(
mostream
,
System
.
Drawing
.
Imaging
.
ImageFormat
.
Bmp
);
bt
=
new
byte
[
mostream
.
Length
];
mostream
.
Position
= 0;
mostream
.
Read
(
bt
, 0,
Convert
.
ToInt32
(
bt
.
Length
));
}
}
return
bt
;
}
4.Image图片缩放
public
Image
pictureProcess
(
Image
sourceImage
,
int
targetWidth
,
int
targetHeight
)
{
int
width
;
//图片最终的宽
int
height
;
//图片最终的高
try
{
System
.
Drawing
.
Imaging
.
ImageFormat
format
=
sourceImage
.
RawFormat
;
Bitmap
targetPicture
=
new
Bitmap
(
targetWidth
,
targetHeight
);
Graphics
graphics
=
Graphics
.
FromImage
(
targetPicture
);
graphics
.
Clear
(
Color
.
White
);
//计算缩放图片的大小
if
(
sourceImage
.
Width
>
targetWidth
&&
sourceImage
.
Height
<=
targetHeight
)
{
width
=
targetWidth
;
height
= (
width
*
sourceImage
.
Height
) /
sourceImage
.
Width
;
}
else
if
(
sourceImage
.
Width
<=
targetWidth
&&
sourceImage
.
Height
>
targetHeight
)
{
height
=
targetHeight
;
width
= (
height
*
sourceImage
.
Width
) /
sourceImage
.
Height
;
}
else
if
(
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
();
return
targetPicture
;
}
catch
(
Exception
ex
)
{
}
return
null
;
}
5.byte[] 转bitmap
public
static
Bitmap
BytesToBitmap
(
byte
[]
Bytes
)
{
MemoryStream
stream
=
null
;
try
{
stream
=
new
MemoryStream
(
Bytes
);
return
new
Bitmap
((
Image
)
new
Bitmap
(
stream
));
}
catch
(
ArgumentNullException
ex
)
{
throw
ex
;
}
catch
(
ArgumentException
ex
)
{
throw
ex
;
}
finally
{
stream
.
Close
();
}
}