1.先封裝一個SDFileHelper方法,通過Glide圖片加載庫保存服務器上的圖片
String filePath = Environment.getExternalStorageDirectory() + File.separator + "A1";,自定義圖片保存的位置
public class SDFileHelper {
private Context context;
public SDFileHelper() {
}
public SDFileHelper(Context context) {
super();
this.context = context;
}
//Glide保存圖片
public void savePicture(final String fileName, String url){
Glide.with(context).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
@Override
public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
try {
savaFileToSD(fileName,bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//往SD卡寫入文件的方法
public void savaFileToSD(String filename, byte[] bytes) throws Exception {
//如果手機已插入sd卡,且app具有讀寫sd卡的權限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String filePath = Environment.getExternalStorageDirectory() + File.separator + "A1";
File dir1 = new File(filePath);
if (!dir1.exists()){
dir1.mkdirs();
}
filename = filePath+ "/" + filename;
//這里就不要用openFileOutput了,那個是往手機內存中寫數據的
FileOutputStream output = new FileOutputStream(filename);
output.write(bytes);
//將bytes寫入到輸出流中
output.close();
//關閉輸出流
Toast.makeText(context, "圖片已成功保存到"+filePath, Toast.LENGTH_SHORT).show();
} else Toast.makeText(context, "SD卡不存在或者不可讀寫", Toast.LENGTH_SHORT).show();
}
}
2.在事件中調用
public class MainActivity extends AppCompatActivity {
private String url = "http://www.vorin.cn/storage/oilImage/test/tim1.jpeg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btn_get);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SDFileHelper helper = new SDFileHelper(MainActivity.this);
helper.savePicture("tim1.jpeg", url);
}
});
}
}
3.若要加載大量圖片
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btn_get);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//100要換掉
for (int i = 1; i < 100; i++) {
String url = "http://www.vorin.cn/storage/oilImage/test/tim" + i + ".jpeg";
//取得最后一個/的下標
int index = url.lastIndexOf("/");
//將字符串轉為字符數組
char[] ch = url.toCharArray();
//根據 copyValueOf(char[] data, int offset, int count) 取得最后一個字符串
String informationId = String.copyValueOf(ch, index + 1, ch.length - index - 1);
SDFileHelper helper = new SDFileHelper(MainActivity.this);
helper.savePicture(informationId, url);
}
}
});
}
}
上述中i要通過接口獲取jsons數據統計文件數量,會在下篇中講到