[英]How to save image from URL into internal or external storage?
这是我的代码,它说no such file or directory
。 谁能帮我这个? 我想将图像从URL保存到存储中。
if (imageLoaded) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (imageBitmap == null) {
Toast.makeText(getActivity(), "Looks like images didn't load.", Toast.LENGTH_SHORT).show();
} else {
imageBitmap.compress(Bitmap.CompressFormat.JPEG,100,bytes);
File directory = null;
if (Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)) {
directory = new File(Environment.getExternalStorageDirectory(),"COC");
if (!directory.isDirectory()) {
directory.mkdirs();
}
}
File f = new File(directory,ImageName+".jpg");
try {
f.createNewFile();
FileOutputStream fo = null;
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
Toast.makeText(getActivity(),"saved",Toast.LENGTH_SHORT).show();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
对于这种情况,选择像Retrofit这样的网络库将是不错的选择。 否则,您必须创建HTTP URL连接,将图像下载为位图,然后将其保存到文件中。 所有工作都需要在主线程上完成。 因此需要大量线程池。 因此,让我们通过改造来解决问题
首先将改造添加为对应用程序级别gradle文件的依赖
compile 'com.squareup.retrofit:retrofit:2.0.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0'
然后创建一个带有图像视图的演示布局文件,在此图像视图中,我们将显示下载的图像
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="1420px"
android:maxHeight="700px"
android:scaleType="fitCenter" />
</RelativeLayout>
之后,让我们创建这样的网络API接口
public interface RetrofitImageAPI {
@GET("retrofit/images/uploads/android.jpg")
Call<ResponseBody> getImageDetails();
}
这是将改装用作sigleton模式的一个好习惯( 请参阅此 )
但是出于演示目的,我在一个活动中展示了所有内容
public class MainActivity extends AppCompatActivity {
String url = "http://www.delaroystudios.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button ButtonArray= (Button) findViewById(R.id.RetrofitImage);
ButtonArray.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View VisibleImage = findViewById(R.id.RetrofitImage);
VisibleImage.setVisibility(View.GONE);
getRetrofitImage();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
void getRetrofitImage() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class);
Call<ResponseBody> call = service.getImageDetails();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
try {
Log.d("onResponse", "Response came from server");
boolean FileDownloaded = DownloadImage(response.body());
Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
private boolean DownloadImage(ResponseBody body) {
try {
Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
FileOutputStream out = null;
try {
in = body.byteStream();
out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "Android.jpg");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
int width, height;
ImageView image = (ImageView) findViewById(R.id.imageViewId);
Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "Android.jpg");
width = 2*bMap.getWidth();
height = 3*bMap.getHeight();
Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false);
image.setImageBitmap(bMap2);
return true;
} catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item)
}
}
如果有帮助,请不要忘记喜欢并单击接受按钮。 对于回答的人来说意义重大。
祝你有美好的一天
使用毕加索:
Picasso.with(mContext)
.load(ImageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
非常简单的代码将位图保存到您选择的目录文件中:
final File myImageFile = new File(FILE_DIRECTORY, IMAGE_NAME); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
IMAGE_BITMAP.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + Uri.parse("file://" + myImageFile.toString()).toString());
如果要使用截击,则可以执行以下操作:
ImageRequest ir = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
final File myImageFile = new File(fileDirectory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
response.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + Uri.parse("file://" + myImageFile.toString()).toString()); downloadedFileUris.add(FileProvider.getUriForFile(ViewReportsActivity.this.getBaseContext(), BuildConfig.APPLICATION_ID + ".provider", myImageFile));
}
}, 0, 0, null, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
您抱怨无法创建文件。 但是您尝试在不存在的目录中写入文件。 在mkdirs()之后,您无需检查目录是否确实已创建。 好吧,不是。
从Android 6开始,您应该在运行时要求用户确认清单中要求的权限。
Google的运行时权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.