草庐IT

Android 将图片网址url转化为bitmap,drawable转bitmap,file转bitmap,bitmap转file,Bitmap转String,Uri转Bitmap

L-AづMEssi 2023-03-28 原文
file转bitmap File param = new File();

Bitmap bitmap= BitmapFactory.decodeFile(param.getPath()); drawable转bitmap Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.mipmap.jcss_03 ); url转bitmap Bitmap bitmap; public Bitmap returnBitMap(final String url){

new Thread(new Runnable() {
@Override
public void run() {
URL imageurl = null;

try {
imageurl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

return bitmap;
}

方法二:

public Bitmap getBitmap(String url) { Bitmap bm = null; try { URL iconUrl = new URL(url); URLConnection conn = iconUrl.openConnection(); HttpURLConnection http = (HttpURLConnection) conn;

int length = http.getContentLength();

conn.connect();
// 获得图像的字符流
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, length);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();// 关闭流
}
catch (Exception e) {
e.printStackTrace();
}
return bm;
}

可配合前台线程显示

private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case REFRESH_COMPLETE: myheadimage.setImageBitmap(bitmap);//显示 break; } } }; String imageUrl = "​​http://www.pp3.cn/uploads/201511/2015111212.jpg​​"; bitmap= returnBitMap(imageUrl); mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 1000); bitmap转file private String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";//

private String SAVE_REAL_PATH = SAVE_PIC_PATH + "/good/savePic";//保存的确 saveFile(bmp, System.currentTimeMillis() + ".png"); //保存方法 private void saveFile(Bitmap bm, String fileName) throws IOException { String subForder = SAVE_REAL_PATH; File foder = new File(subForder); if (!foder.exists()) foder.mkdirs();

File myCaptureFile = new File(subForder, fileName);
Log.e("lgq","图片保持。。。。wwww。。。。"+myCaptureFile);
ends = myCaptureFile.getPath();
if (!myCaptureFile.exists()) myCaptureFile.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
// ToastUtil.showSuccess(getApplicationContext(), "已保存在/good/savePic目录下", Toast.LENGTH_SHORT); //发送广播通知系统 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(myCaptureFile); intent.setData(uri); this.sendBroadcast(intent); }

Uri转Bitmap public static Bitmap decodeUri(Context context, Uri uri, int maxWidth, int maxHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; //只读取图片尺寸 readBitmapScale(context, uri, options);

//计算实际缩放比例
int scale = 1;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if ((options.outWidth / scale > maxWidth &&
options.outWidth / scale > maxWidth * 1.4) ||
(options.outHeight / scale > maxHeight &&
options.outHeight / scale > maxHeight * 1.4)) {
scale++;
} else {
break;
}
}

options.inSampleSize = scale;
options.inJustDecodeBounds = false;//读取图片内容
options.inPreferredConfig = Bitmap.Config.RGB_565; //根据情况进行修改
Bitmap bitmap = null;
try {
bitmap = readBitmapData(context, uri, options);
} catch (Throwable e) {
e.printStackTrace();
}
return bitmap;
}

‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’

频繁setImageBitmap引起oom问题解决方法 Glide.with(gsewmimg).load(getCodeBitmap(response.data.skip, R.mipmap.zhifuicon)).into(gsewmimg); 压缩前后。图片大小 2.22MB——>200KB

1、图片压缩方法:

Bitmap bitmap; byte[] buff; buff = Bitmap2Bytes(bitmap); BitmapFactory.Options ontain = new BitmapFactory.Options(); ontain.inSampleSize = 7;//值1为原图。值越大,压缩图片越小1-20 bitmap = BitmapFactory.decodeByteArray(buff, 0, buff.length, ontain);

压缩方法2:

int height = (int) ( mybitmap.getHeight() * (512.0 / mybitmap.getWidth()) ); mybitmap = Bitmap.createScaledBitmap(mybitmap, 512, height, true);

2、bitmap转byte

private byte[] Bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); }

3、byte转bitmap

private Bitmap Bytes2Bimap(byte[] b) { if (b.length != 0) { return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } }

方法二,bitmap 转byte Bitmap frame = mCamera != null ? mCamera.Snapshot(mSelectedChannel) : null; frame = rotate(frame, 90); byte[] snapshot = getByteArrayFromBitmap(frame); if (snapshot!=null){ String imageString = new String(Base64.encode(snapshot,Base64.DEFAULT)); // LgqLogPlus.e("获取到imgstring保存了===== "+imageString); SharedPreUtil.putString(mDevUID,imageString); } public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {

if (bitmap != null && !bitmap.isRecycled()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
return bos.toByteArray();
} else {
return null;
}
} byte转bitmap String imgstring = SharedPreUtil.getString(this,mDevUID); // LgqLogPlus.e("获取到imgstring==== "+imgstring); if (imgstring!=null){ byte[] bytsSnapshot = Base64.decode(imgstring.getBytes(), Base64.DEFAULT); Bitmap snapshot = (bytsSnapshot != null && bytsSnapshot.length > 0) ? getBitmapFromByteArray(bytsSnapshot) : null; bgimg.setImageBitmap(snapshot); } public static Bitmap getBitmapFromByteArray(byte[] byts) {

InputStream is = new ByteArrayInputStream(byts);
return BitmapFactory.decodeStream(is, null, getBitmapOptions(2));
}

public static BitmapFactory.Options getBitmapOptions(int scale) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = scale;

try {
BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return options;
} 旋转方法: //Rotate Bitmap public final static Bitmap rotate(Bitmap b, float degrees) { if (degrees != 0 && b != null) { Matrix m = new Matrix(); m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);

Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}

}
return b;
}

调用 bitmap = rotate(bitmap,90); 效果 选图

Android报错:Throwing OutOfMemoryError failed to allocate a 42793710 byte allocation with 52488 free by 在里加上android:hardwareAccelerated="false" 和 android:largeHeap="true"成功解决

Bitmap与String互转 Bitmap frame = BitmapFactory.decodeResource(getResources(),R.mipmap.iv_charge2 );

byte[] snapshot = getByteArrayFromBitmap(frame);

if (snapshot!=null){ String imageString = new String(Base64.encode(snapshot,Base64.DEFAULT));

if (imageString!=null){
byte[] bytsSnapshot = Base64.decode(imageString.getBytes(), Base64.DEFAULT);
Bitmap snapshot2 = (bytsSnapshot != null && bytsSnapshot.length > 0) ? getBitmapFromByteArray(bytsSnapshot) : null;
imageView.setImageBitmap(snapshot2);
}
}


工具:

public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {

if (bitmap != null && !bitmap.isRecycled()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
return bos.toByteArray();
} else {
return null;
}
}

public static Bitmap getBitmapFromByteArray(byte[] byts) {

InputStream is = new ByteArrayInputStream(byts);
return BitmapFactory.decodeStream(is, null, getBitmapOptions(2));
}

public static BitmapFactory.Options getBitmapOptions(int scale) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = scale;

try {
BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return options;
} private static void readBitmapScale(Context context, Uri uri, BitmapFactory.Options options) { if (uri == null) { return; } String scheme = uri.getScheme(); if (ContentResolver.SCHEME_CONTENT.equals(scheme) || ContentResolver.SCHEME_FILE.equals(scheme)) { InputStream stream = null; try { stream = context.getContentResolver().openInputStream(uri); BitmapFactory.decodeStream(stream, null, options); } catch (Exception e) { Log.w("readBitmapScale", "Unable to open content: " + uri, e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { Log.e("readBitmapScale", "Unable to close content: " + uri, e); } } } } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) { Log.e("readBitmapScale", "Unable to close content: " + uri); } else { Log.e("readBitmapScale", "Unable to close content: " + uri); } }

private static Bitmap readBitmapData(Context context, Uri uri, BitmapFactory.Options options) { if (uri == null) { return null; } Bitmap bitmap = null; String scheme = uri.getScheme(); if (ContentResolver.SCHEME_CONTENT.equals(scheme) || ContentResolver.SCHEME_FILE.equals(scheme)) { InputStream stream = null; try { stream = context.getContentResolver().openInputStream(uri); bitmap = BitmapFactory.decodeStream(stream, null, options); } catch (Exception e) { Log.e("readBitmapData", "Unable to open content: " + uri, e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { Log.e("readBitmapData", "Unable to close content: " + uri, e); } } } } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) { Log.e("readBitmapData", "Unable to close content: " + uri); } else { Log.e("readBitmapData", "Unable to close content: " + uri); } return bitmap; }



有关Android 将图片网址url转化为bitmap,drawable转bitmap,file转bitmap,bitmap转file,Bitmap转String,Uri转Bitmap的更多相关文章

  1. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  2. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  3. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  4. ruby CSV : How can I read a tab-delimited file? - 2

    CSV.open(name,"r").eachdo|row|putsrowend我得到以下错误:CSV::MalformedCSVErrorUnquotedfieldsdonotallow\ror\n文件名是一个.txt制表符分隔文件。我是专门做的。我有一个.csv文件,我转到excel,并将文件保存为.txt制表符分隔的文件。所以它是制表符分隔的。CSV.open不应该能够读取制表符分隔的文件吗? 最佳答案 尝试像这样指定字段分隔符:CSV.open("name","r",{:col_sep=>"\t"}).eachdo|row|

  5. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  6. ruby-on-rails - 将 Ruby 中的日期/时间格式化为 YYYY-MM-DD HH :MM:SS - 2

    这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build

  7. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  8. ruby-on-rails - Ruby on Rails - 为文本区域和图片生成列 - 2

    我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数

  9. ruby - 字符串文字中的转义状态作为 `String#tr` 的参数 - 2

    对于作为String#tr参数的单引号字符串文字中反斜杠的转义状态,我觉得有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用了'd',在双引号中转义时不会改变含义("\d"="d")。'\\'.tr('\\','x')#=>"x"'\\'.tr('\\d','x')#=>"\\"'\\'.tr('\\\d','x')#=>"x" 最佳答案 在tr中转义tr的第一个参数非常类似于正则表达式中的括号字符分组。您可以在表达式的开头使用^来否定匹配(替换任何不匹配的内容)并使用例如a-f来匹配一

  10. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

随机推荐