简而言之,我无法使用inSampleSize调整我的图像文件(高度为475像素)。代码如下。
在代码之后,图像应该减少到237.5像素,不是吗?但它保持不变,与原始尺寸完全相同。
任何人都可以帮忙。
File f = new File(context.getCacheDir(), "1223fdf");
URL imageUrl = new URL("http://example.com/file.jpg");
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(false);
String url = conn.getHeaderField("Location");
URL redirectURL = new URL(url);
URLConnection redirectConn = redirectURL.openConnection();
InputStream is=redirectConn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_SIZE=200;
int height_tmp=o.outHeight; // This returns 475
int scale=1;
while(true){
if(height_tmp/2<REQUIRED_SIZE)
break;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale; //SCALE = 2 here (checked by printing in LogCat)
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
return bmp;
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}