Android Socket服务端与客户端用字符串的方式互相传递图片的方法
发送图片:
首先找到具体传递的图片:
<spanstyle="font-family:comicsansms,sans-serif;font-size:16px;">privateBitmapgetimage(StringsrcPath){
BitmapFactory.OptionsnewOpts=newBitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds设回true了
newOpts.inJustDecodeBounds=true;
Bitmapbitmap=BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
newOpts.inJustDecodeBounds=false;
intw=newOpts.outWidth;
inth=newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
floathh=100f;//这里设置高度为800f
floatww=100f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
intbe=1;//be=1表示不缩放
if(w>h&&w>ww){//如果宽度大的话根据宽度固定大小缩放
be=(int)(newOpts.outWidth/ww);
}elseif(w<h&&h>hh){//如果高度高的话根据宽度固定大小缩放
be=(int)(newOpts.outHeight/hh);
}
if(be<=0)
be=1;
newOpts.inSampleSize=be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds设回false了
bitmap=BitmapFactory.decodeFile(srcPath,newOpts);
returncompressImage(bitmap);//压缩好比例大小后再进行质量压缩
}
</span>
下面的方法是压缩图片的方法
<spanstyle="font-family:comicsansms,sans-serif;font-size:px;">privateBitmapcompressImage(Bitmapimage){
ByteArrayOutputStreambaos=newByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG,,baos);//质量压缩方法,这里表示不压缩,把压缩后的数据存放到baos中
intoptions=;
while(baos.toByteArray().length/>){//循环判断如果压缩后图片是否大于kb,大于继续压缩
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG,options,baos);//这里压缩options%,把压缩后的数据存放到baos中
options-=;//每次都减少
}
ByteArrayInputStreamisBm=newByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmapbitmap=BitmapFactory.decodeStream(isBm,null,null);//把ByteArrayInputStream数据生成图片
returnbitmap;
}
</span>
将bitmap转化为byte[]数组
<spanstyle="font-family:comicsansms,sans-serif;font-size:16px;">publicbyte[]Bitmap2Bytes(Bitmapbm){
ByteArrayOutputStreambaos=newByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG,100,baos);
returnbaos.toByteArray();
}
</span>
格式化byte成字符串
<spanstyle="font-family:comicsansms,sans-serif;font-size:px;">/**
*格式化byte
*
*@paramb
*@return
*/
publicstaticStringbytehex(byte[]b){
char[]Digit={'','','','','','','','','','','A',
'B','C','D','E','F'};
char[]out=newchar[b.length*];
for(inti=;i<b.length;i++){
bytec=b[i];
out[i*]=Digit[(c>>>)&XF];
out[i*+]=Digit[c&XF];
}
returnnewString(out);
}
</span>
接收图片:
首先将传递过来的String转化成byte[]数组:
<spanstyle="font-family:comicsansms,sans-serif;font-size:px;">/**
*反格式化byte
*
*@params
*@return
*/
publicstaticbyte[]hexbyte(Strings){
byte[]src=s.toLowerCase().getBytes();
byte[]ret=newbyte[src.length/];
for(inti=;i<src.length;i+=){
bytehi=src[i];
bytelow=src[i+];
hi=(byte)((hi>='a'&&hi<='f')?xa+(hi-'a')
:hi-'');
low=(byte)((low>='a'&&low<='f')?xa+(low-'a')
:low-'');
ret[i/]=(byte)(hi<<|low);
}
returnret;
}
</span>
将byte[]转化成bitmap:
<spanstyle="font-family:comicsansms,sans-serif;font-size:px;">publicBitmapBytesBimap(byte[]b){
if(b.length!=){
returnBitmapFactory.decodeByteArray(b,,b.length);
}else{
returnnull;
}
}
</span>
使用android中的setImageBitmap方法就可以将接收到的图片显示到手机了。
