图片与字节数组相互转换的方法
C#byte数组与Image的相互转换

C#byte数组与Image的相互转换功能需求:1、把⼀张图⽚(png bmp jpeg bmp gif)转换为byte数组存放到数据库。
2、把从数据库读取的byte数组转换为Image对象,赋值给相应的控件显⽰。
3、从图⽚byte数组得到对应图⽚的格式,⽣成⼀张图⽚保存到磁盘上。
这⾥的Image是System.Drawing.Image。
//Get an image from fileImage image = Image.FromFile("D:\\test.jpg");Bitmap bitmap = new Bitmap("D:\\test.jpg");以下三个函数分别实现了上述三个需求:using System;using System.Collections.Generic;using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Linq;using System.Text;namespace NetUtilityLib{public static class ImageHelper{///<summary>/// Convert Image to Byte[]///</summary>///<param name="image"></param>///<returns></returns>public static byte[] ImageToBytes(Image image){ImageFormat format = image.RawFormat;using (MemoryStream ms = new MemoryStream()){if (format.Equals(ImageFormat.Jpeg)){image.Save(ms, ImageFormat.Jpeg);}else if (format.Equals(ImageFormat.Png)){image.Save(ms, ImageFormat.Png);}else if (format.Equals(ImageFormat.Bmp)){image.Save(ms, ImageFormat.Bmp);}else if (format.Equals(ImageFormat.Gif)){image.Save(ms, ImageFormat.Gif);}else if (format.Equals(ImageFormat.Icon)){image.Save(ms, ImageFormat.Icon);}byte[] buffer = new byte[ms.Length];//Image.Save()会改变MemoryStream的Position,需要重新Seek到Beginms.Seek(0, SeekOrigin.Begin);ms.Read(buffer, 0, buffer.Length);return buffer;}}///<summary>/// Convert Byte[] to Image///</summary>///<param name="buffer"></param>///<returns></returns>public static Image BytesToImage(byte[] buffer){MemoryStream ms = new MemoryStream(buffer);Image image = System.Drawing.Image.FromStream(ms);return image;}///<summary>/// Convert Byte[] to a picture and Store it in file///</summary>///<param name="fileName"></param>///<param name="buffer"></param>///<returns></returns>public static string CreateImageFromBytes(string fileName, byte[] buffer) {string file = fileName;Image image = BytesToImage(buffer);ImageFormat format = image.RawFormat;if (format.Equals(ImageFormat.Jpeg)){file += ".jpeg";}else if (format.Equals(ImageFormat.Png)){file += ".png";}else if (format.Equals(ImageFormat.Bmp)){file += ".bmp";}else if (format.Equals(ImageFormat.Gif)){file += ".gif";}else if (format.Equals(ImageFormat.Icon)){file += ".icon";}System.IO.FileInfo info = new System.IO.FileInfo(file);System.IO.Directory.CreateDirectory(info.Directory.FullName);File.WriteAllBytes(file, buffer);return file;}}}。
java bufferedimage转bytes方法

java bufferedimage转bytes方法Java BufferedImage转Bytes方法介绍在Java编程中,我们常常需要将BufferedImage对象转化为字节数组(byte array),以便进行进一步的处理或传输。
这篇文章将详细介绍一些常用的方法,帮助你实现这一目标。
方法一:使用ByteArrayOutputStream该方法通过创建一个ByteArrayOutputStream对象,并使用ImageIO将BufferedImage写入流中,最后将流转化为字节数组。
ByteArrayOutputStream baos = new ByteArrayOutputStr eam();(image, "jpg", baos);byte[] bytes = ();方法二:使用MemoryCacheImageOutputStream这种方法需要使用类,先将BufferedImage对象写入MemoryCacheImageOutputStream对象中,然后从中获取字节数组。
try (MemoryCacheImageOutputStream os = new MemoryCa cheImageOutputStream(baos)) {(image, "png", os);();byte[] bytes = ();}方法三:使用RasterRaster类提供了获取BufferedImage数据的一种方法,我们可以通过getDataBuffer()获取DataBuffer对象,进而获取字节数组。
WritableRaster raster = ();DataBufferByte buffer = (DataBufferByte) ();byte[] bytes = ();方法四:使用PixelGrabberPixelGrabber类可以用来抓取图像中的像素信息,我们可以利用该类获取图像的字节数组。
图片二进制互相转换C#

Response.ContentType = "application/x-shockwave-flash";
case "xls":
Response.ContentType = "application/vnd.ms-excel";
case "gif":
Response.ContentType = "image/gif";
//img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
//下面几行代码将图片显示在IMAGE中
byte[] photo = getBytes(strpath);
二进制文件转换部分:
string strpath;
protected void Page_Load(object sender, EventArgs e)
{
strpath = HttpContext.Current.Request.PhysicalApplicationPath + "1.bmp";
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(imgData);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
case "Jpg":
Response.ContentType = "image/jpeg";
图片转二进制(互转)

图⽚转⼆进制(互转)Note:图⽚转⼆进制数据只需转化为bate数组⼆进制数据即可,例如要求httpclient发送图⽚⼆进制数据即是把⽣成的bate数组数据发送过去。
如果对⽅明确提出是字符串格式编码,再进⼀步转化就好了使⽤Base64转换图⽚利⽤Base64实现⼆进制和图⽚之间的转换,具体代码如下:import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import org.apache.tomcat.util.codec.binary.Base64;public class ImageBinary {public static void main(String[] args) {String fileName = "D://code//test.jpg";System.out.println(getImageBinary(fileName));saveImage(getImageBinary(fileName));}/** 图⽚转换为⼆进制** @param fileName* 本地图⽚路径* @return* 图⽚⼆进制流* */public static String getImageBinary(String fileName) {File f = new File(fileName);BufferedImage bi;try {bi = ImageIO.read(f);ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(bi, "jpg", baos);byte[] bytes = baos.toByteArray();return Base64.encodeBase64String(bytes);//return encoder.encodeBuffer(bytes).trim();} catch (IOException e) {e.printStackTrace();}return null;}/*** 将⼆进制转换为图⽚** @param base64String* 图⽚⼆进制流**/public static void saveImage(String base64String) {try {byte[] bytes1 = Base64.decodeBase64(base64String);ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);BufferedImage bi1 = ImageIO.read(bais);File w2 = new File("D://code//22.jpg");// 可以是jpg,png,gif格式ImageIO.write(bi1, "jpg", w2);// 不管输出什么格式图⽚,此处不需改动} catch (IOException e) {e.printStackTrace();}}}⽹络地址url与本地图⽚获取图⽚字节流若通过url访问图⽚并转换为⼆进制流,就不能按照上述⽅法。
C#图片和byte[]的互相转换
![C#图片和byte[]的互相转换](https://img.taocdn.com/s3/m/00c327de85254b35eefdc8d376eeaeaad1f3168d.png)
C#图⽚和byte[]的互相转换图⽚的“读”操作①参数是图⽚路径:返回Byte[]类型://参数是图⽚的路径public byte[] GetPictureData(string imagePath){FileStream fs = new FileStream(imagePath, FileMode.Open);byte[] byteData = new byte[fs.Length];fs.Read(byteData, 0, byteData.Length);fs.Close();return byteData;}②参数类型是Image对象,返回Byte[]类型//将Image转换成流数据,并保存为byte[]public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto){MemoryStream mstream = new MemoryStream();imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);byte[] byData = new Byte[mstream.Length];mstream.Position = 0;mstream.Read(byData, 0, byData.Length); mstream.Close();return byData;}图⽚的“写”操作①参数是Byte[]类型,返回值是Image对象public System.Drawing.Image ReturnPhoto(byte[] streamByte){System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);System.Drawing.Image img = System.Drawing.Image.FromStream(ms);return img;}②参数是Byte[] 类型,没有返回值(输出图⽚)public void WritePhoto(byte[] streamByte){// Response.ContentType 的默认值为默认值为“text/html”Response.ContentType = "image/GIF";//图⽚输出的类型有: image/GIF image/JPEGResponse.BinaryWrite(streamByte);}。
c# 图片与byte[]之间以及byte[]与string之间的转换
![c# 图片与byte[]之间以及byte[]与string之间的转换](https://img.taocdn.com/s3/m/8e1cd70a03d8ce2f00662398.png)
return ms.ToArray();
}
public static string ByteArrayToString(byte[] bytes)
{
return Convert.ToBase64String(bytes);
winform直接显示二进制数据中的图片
//读取DataSet中以二进制(Image)形式保存的图片
byte[] byteImage = (byte[])dataSet11.tBGPicture.Rows[2]["PicContent"];
//转成MemoryStream类型
10 ms2.Seek(0, System.IO.SeekOrigin.Begin);
11 System.Drawing.Image image2 = System.Drawing.Image.FromStream(ms2);
12 image2.Save("D:\\2.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Image image = Image.FromStream(ms);
return image;
}
public static byte[] ImageToByteArray(Image image)
{
MemoryStream ms = new MemoryStream();
3 image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
4 ms.Flush();
VC打开图片保存为数组,然后数组显示为图片,直接操作像素值

显示.bmp文件:操作xxDoc.h, xxDoc.cpp, xxView.cpp即可完成1、新建单文档文件BmpView2、在BmpViewDoc.h中添加// Attributespublic:BITMAPINFOHEADER bi; //信息头RGBQUAD* quad; //调色板BYTE* lpBuf; //图像数据BITMAPINFO* pbi;int flag; //标志表示是否打开了bmp文件,并在构造函数中初始化为0,Sorinleeint numQuad; //调色板数目BYTE* lpshowbuf; //用于显示的图像数据int zoomfactor; //缩放比率BYTE** image; //原文是把它作为局部变量,在PrepareShowdata()函数中定义Sorinlee3、在BmpViewDoc.cpp的OnFileOpen() 中添加// TODO: Add your command handler code hereflag=1;//设定标志SorinleeLPCTSTR lpszFilter="BMP Files(*.bmp)|*.bmp|任何文件|*.*||";CFileDialogdlg1(TRUE,lpszFilter,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,lpszFilter,NULL); CString filename;CFile file;BITMAPFILEHEADER bf;//打开文件对话框if(dlg1.DoModal()==IDOK){filename=dlg1.GetPathName();if(file.Open(filename,CFile::modeRead|CFile::shareDenyNone,NULL)==0){//读取文件失败AfxMessageBox("无法打开文件!",MB_OK,0);return;}//读取文件头file.Read(&bf,sizeof(bf));//判断是否是BMP文件if(bf.bfType!=0x4d42)//'BM'{AfxMessageBox("非BMP文件!",MB_OK,0);return;}//判断文件是否损坏if(file.GetLength()!=bf.bfSize){AfxMessageBox("文件已损坏,请检查!",MB_OK,0);return;}//读文件信息头file.Read(&bi,sizeof(bi));//计算调色板数目numQuad=0;if(bi.biBitCount<24){numQuad=1<<bi.biBitCount;}//为图像信息pbi申请空间pbi=(BITMAPINFO*)HeapAlloc(GetProcessHeap(),0,sizeof(BITMAPINFOHEADER)+numQuad*sizeof(R GBQUAD));memcpy(pbi,&bi,sizeof(bi));quad=(RGBQUAD*)((BYTE*)pbi+sizeof(BITMAPINFOHEADER));//读取调色板if(numQuad!=0){file.Read(quad,sizeof(RGBQUAD)*numQuad);}//为图像数据申请空间bi.biSizeImage=bf.bfSize-bf.bfOffBits;lpBuf=(BYTE*)HeapAlloc(GetProcessHeap(),0,bi.biSizeImage);//读取图像数据file.Read(lpBuf,bi.biSizeImage);//图像读取完毕,关闭文件,设置标志file.Close();flag=1;zoomfactor=1;lpshowbuf=NULL;PrepareShowdata();UpdateAllViews(NULL,0,NULL);}4、在BmpViewDoc 中添加成员函数bool CBmpViewDoc::PrepareShowdata()//BYTE** image;//原文是在这里把这个定义为局部变量SorinleeBYTE** originimage;int i,j;int linewidth;if(lpshowbuf!=NULL)HeapFree(GetProcessHeap(),0,lpshowbuf);if(zoomfactor>=1){//放大pbi->bmiHeader.biHeight=bi.biHeight*zoomfactor;pbi->bmiHeader.biWidth=bi.biWidth*zoomfactor;//每行四字节补齐,计算每行字节数:linewidth=(pbi->bmiHeader.biWidth*pbi->bmiHeader.biBitCount+31)/32*4;//计算显示图像所需内存大小pbi->bmiHeader.biSizeImage=linewidth*pbi->bmiHeader.biHeight;//申请内存lpshowbuf=(BYTE*)HeapAlloc(GetProcessHeap(),0,pbi->bmiHeader.biSizeImage); //生成对lpshowbuf的二维数组索引:image=new BYTE*[pbi->bmiHeader.biHeight];for(i=0;i<pbi->bmiHeader.biHeight;i++)image[i]=lpshowbuf+i*linewidth;originimage=new BYTE*[bi.biHeight];for(i=0;i<bi.biHeight;i++)originimage[i]=lpBuf+i*bi.biSizeImage/bi.biHeight;//赋值if(bi.biBitCount<24){for(i=0;i<pbi->bmiHeader.biHeight;i++)for(j=0;j<linewidth;j++)image[i][j]=originimage[i/zoomfactor][j/zoomfactor];}else if(bi.biBitCount==24){//24位真彩色for(i=0;i<pbi->bmiHeader.biHeight;i++)for(j=0;j<pbi->bmiHeader.biWidth;j++){image[i][j*3]=originimage[i/zoomfactor][(j/zoomfactor)*3];image[i][j*3+1]=originimage[i/zoomfactor][(j/zoomfactor)*3+1];image[i][j*3+2]=originimage[i/zoomfactor][(j/zoomfactor)*3+2];}}else{//32位色for(i=0;i<pbi->bmiHeader.biHeight;i++)for(j=0;j<pbi->bmiHeader.biWidth;j++){image[i][j*4]=originimage[i/zoomfactor][(j/zoomfactor)*4];image[i][j*4+1]=originimage[i/zoomfactor][(j/zoomfactor)*4+1];image[i][j*4+2]=originimage[i/zoomfactor][(j/zoomfactor)*4+2];image[i][j*4+3]=originimage[i/zoomfactor][(j/zoomfactor)*4+3];}}}else{//缩小pbi->bmiHeader.biHeight=bi.biHeight/(-zoomfactor);pbi->bmiHeader.biWidth=bi.biWidth/(-zoomfactor);//每行四字节补齐,计算每行字节数:linewidth=(pbi->bmiHeader.biWidth*pbi->bmiHeader.biBitCount+31)/32*4;//计算显示图像所需内存大小pbi->bmiHeader.biSizeImage=linewidth*pbi->bmiHeader.biHeight;//申请内存lpshowbuf=(BYTE*)HeapAlloc(GetProcessHeap(),0,pbi->bmiHeader.biSizeImage); //生成对lpshowbuf的二维数组索引:image=new BYTE*[pbi->bmiHeader.biHeight];for(i=0;i<pbi->bmiHeader.biHeight;i++)image[i]=lpshowbuf+i*linewidth;originimage=new BYTE*[bi.biHeight];for(i=0;i<bi.biHeight;i++)originimage[i]=lpBuf+i*bi.biSizeImage/bi.biHeight;//赋值if(bi.biBitCount<24){for(i=0;i<pbi->bmiHeader.biHeight;i++)for(j=0;j<linewidth;j++)image[i][j]=originimage[i*(-zoomfactor)][j*(-zoomfactor)];}else if(bi.biBitCount==24){//24位真彩色for(i=0;i<pbi->bmiHeader.biHeight;i++)for(j=0;j<pbi->bmiHeader.biWidth;j++){image[i][j*3]=originimage[i*(-zoomfactor)][(j*(-zoomfactor))*3];image[i][j*3+1]=originimage[i*(-zoomfactor)][(j*(-zoomfactor))*3+1];image[i][j*3+2]=originimage[i*(-zoomfactor)][(j*(-zoomfactor))*3+2];}}else{//32位色for(i=0;i<pbi->bmiHeader.biHeight;i++)for(j=0;j<pbi->bmiHeader.biWidth;j++){image[i][j*4]=originimage[i*(-zoomfactor)][(j*(-zoomfactor))*4];image[i][j*4+1]=originimage[i*(-zoomfactor)][(j*(-zoomfactor))*4+1];image[i][j*4+2]=originimage[i*(-zoomfactor)][(j*(-zoomfactor))*4+2];image[i][j*4+3]=originimage[i*(-zoomfactor)][(j*(-zoomfactor))*4+3];}}}Invalidate();//使窗口重绘Sorinlee,不明白为什么,不加这句就不显示图像了delete []image;delete []originimage;return TRUE;5、在BmpViewView中添加WM_PAINT消息,在消息响应函数中添加CPaintDC dc(this); // device context for painting// TODO: Add your message handler code here//得到文档指针CBmpViewDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);//是否已打开某个BMP文件,为了直接操作数组的每一个像素,我屏蔽掉了if语句里面的内容Sorinlee if(pDoc->flag==1){//指定是显示的颜色SetDIBitsToDevice(dc.m_hDC,0,0,pDoc->pbi->bmiHeader.biWidth,pDoc->pbi->bmiHeader.biHeight,0,0,0,pDoc->pbi->bmiHeader.biHeight,pDoc->lpshowbuf,pDoc->pbi,DIB_RGB_COLORS);}// Do not call CView::OnPaint() for painting messagesif(flag){//for(int i=0;i<pbi->bmiHeader.biHeight;i++)//图像倒立for(int i= pbi->bmiHeader.biHeight-1;i>0;i--)//图像正显for(int j=0;j<pbi->bmiHeader.biWidth;j++)//dc.SetPixel(i,j,RGB(image[i][j*3],image[i][j*3+1],image[i][j*3+2]));dc.SetPixel(i,j,RGB(image[i][j*3+2],image[i][j*3+1],image[i][j*3]));}把图像显示为点阵形式Sorinlee//创建画笔,画点阵COLORREF c olor;CPoint point(40,40);if(flag){//for(i=0;i<pbi->bmiHeader.biHeight;i++)//图像倒立for(i= pbi->bmiHeader.biHeight-1;i>0;i--)//图像正显{for(j=0;j<pbi->bmiHeader.biWidth;j++){CPen pen(PS_SOLID,5,color);dc.SelectObject(&pen);CBrush *pBrush=CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH));dc.SelectObject(pBrush);//dc.SetPixel(i,j,RGB(image[i][j*3],image[i][j*3+1],image[i][j*3+2]));color=RGB(image[i][j*3],image[i][j*3+1],image[i][j*3+2]);dc.Ellipse(point.x-2,point.y-2,point.x+2,point.y+2);point.x+=12;}point.y+=12;point.x=40;}} */。
java文件File与byte[]数组相互转换的两种方式
![java文件File与byte[]数组相互转换的两种方式](https://img.taocdn.com/s3/m/2210c2bad0f34693daef5ef7ba0d4a7303766c5f.png)
java⽂件File与byte[]数组相互转换的两种⽅式1.⽂件转byte[]⽅式⼀:⽂件输⼊流File file = new File("C:\\Users\\Marydon\\Desktop\\个⼈信⽤报告.pdf");try {FileInputStream fis = new FileInputStream(file);// 强转成int类型⼤⼩的数组byte[] fileBytes = new byte[(int) file.length()];// 将pdf内容放到数组当中fis.read(fileBytes);// 关闭⽂件流fis.close();System.out.println(Arrays.toString(fileBytes));} catch (IOException e) {e.printStackTrace();} 在这⾥会触发⼀个思考题: 将⽂件的长度类型long强制转换成int,真的可以吗? 起初,我觉得这样不妥,原因在于:假设当⽂件的长度>Integer类型的最⼤值时,那就这样肯定就不⾏了,byte[]将不是⼀个完整的⽂件数组集合,怎么办? 我⾸先想到的是: 我们在进⾏⽂件流的读写操作时,通常使⽤的是这种⽅式 写到这⾥,我才明⽩,这种循环读取的⽅式是因为有地⽅可以接受读取到的字节,我们这⾥呢?本来就是要⽤数组接收的,现在接收不下,没有办法,要想实现的话,也就只能将⽂件拆分成多个数字集合,这样⼀来,和我的初衷背道⽽驰,我就是想要将它们融合到⼀个数组,显然,这种⽅式是⾏不通的。
接下来,我就查了在Java中,数组的最⼤限制相关信息: 数组的最⼤限制,理论值是: 相当于2G的⼤⼩,对应应⽤内存的话是4G(源⾃⽹络,不知其真假性,如果有好⼼⼈进⾏测试⼀下,欢迎留⾔) 当我创建⼀个最⼤的数组时,结果如下: 数组所需内存超过了Java虚拟机的内存,GAME OVER。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
图片与字节数组相互转换的方法
图片与字节数组相互转换的方法
aspx.cs
 
using System;using System.IO;
using System.Drawing;
using
System.Drawing.Imaging;public partial class _2Stream : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}protected void FileToStream(object sender, EventArgs e)
{
//将JPG图片转化成字节数组
Image image =
Image.FromFile("E:/1.jpg"); //或者使用Server.MapPath MemoryStream ms =
new MemoryStream();
image.Save(ms,
ImageFormat.Jpeg);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[]
buffer = new byte[ms.Length];
ms.Read(buffer, 0,
(int)ms.Length);//遍历字节数组
for (int i = 0; i <
buffer.LongLength; i++)
{
message.Text +=
buffer[i].ToString();
}//将字节数组转化成图像文件(自定义格式)并保存MemoryStream
ms2 = new MemoryStream(buffer, 0, buffer.Length); ms2.Seek(0,
SeekOrigin.Begin);
Image image2 =
Image.FromStream(ms2);
image2.Save("E:\\2.gif", ImageFormat.Gif);
}
 
aspx
 
<asp:Button runat="server" Text="转换"
onclick="FileToStream"
/>
<asp:TextBox ID="message" runat="server"
Width="100%" Height="600px"
TextMode="MultiLine"
Wrap="true"></asp:TextBox>
 
参考资料
如何将jpg格式图像文件转化成一系列二进制数据,又如何将此二进制数据转化成jpg格式的文件?
/begincsdn/archive/2005/07/12/19 1664.html
如何通过一个图片的URL得到该图片的尺寸大小?
/begincsdn/archive/2005/07/12/19 1663.html为了您的安全,请只打开来源可靠的网址
打开网站取消来自:
/%B4%F3%CE%B0/blog/item/39344dc 269f3b524e4dd3b63.html。