ios 调用writeToFile将图片保存到本地一直失败的解决方案
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ios 调用writeToFile将图片保存到本地一直失败的解决方案相关的知识,希望对你有一定的参考价值。
参考技术A 该问题纠结了我半天时间。。。查了很多资料,最后才发现调用writeToFile返回false的原因。在此附上解决方案:NSData *imageData = UIImageJPEGRepresentation(currentImage, 1.0f);//currentImage是传过来的UIImage
NSString *inewImageName=[self getImagePath:imageName];//imageName为图片名称
BOOL operation = [imageData writeToFile:newImageName options:NSAtomicWrite error:&error];
方法:
- (NSString*)getImagePath:(NSString *)name
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *finalPath = [docPath stringByAppendingPathComponent:name];
// Remove the filename and create the remaining path
[fileManager createDirectoryAtPath:[finalPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];//stringByDeletingLastPathComponent是关键
return finalPath;
希望能帮助大家解决问题哈~
Android下载图片/调用系统相机拍照显示并保存到本地
package com.example.testhttpget; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity { ImageView iamgeview = null; Handler myHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: iamgeview.setImageBitmap((Bitmap)msg.obj); break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView hello = (TextView)findViewById(R.id.hello); iamgeview = (ImageView)findViewById(R.id.imageview); // 子线程网络下载图片 new Thread(){ public void run(){ String imgurl = "http://photocdn.sohu.com/20111123/Img326603573.jpg"; HttpGet mHttpGet = new HttpGet(imgurl); // HttpGet mHttpGet = new HttpGet("http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E7%86%8A%E7%8" + // "C%AB&step_word=&hs=0&pn=0&spn=0&di=28270682580&pi=&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=404637145%2C3982267385&os=3438506744%2C3869227355&simid=0%2C0&adpicid=0&ln=1975&fr=&fmq=1475036112689_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=11&oriquery=&objurl=http%3A%2F%2Fpic4.40017.cn%2Fscenery%2Fdestination%2F2016%2F07%2F17%2F16%2FNylDjq.jpg" ); HttpClient mHtppClient = new DefaultHttpClient(); try{ // 发送get请求并获得相应对象 HttpResponse httpRespose = mHtppClient.execute(mHttpGet); // 取得消息实体 HttpEntity entrie = httpRespose.getEntity(); // 从消息实体取得输入流 InputStream inputstream = entrie.getContent(); // 将输入流转化成BufferedReader BufferedReader bufferReader = new BufferedReader( new InputStreamReader(inputstream)); String result = ""; String line = ""; // for(;(line = bufferReader.readLine())!=null;){ // result += line ; // } // hello.setText(result); Bitmap bitmap = BitmapFactory.decodeStream(inputstream); saveImg2SDcard(bitmap,"/WebTakePhone.jpg"); Message msg = new Message(); msg.obj = bitmap; msg.what = 1; myHandler.sendMessage(msg); }catch(Exception e){ // hello.setText("请求错误"+e.toString()); }; } }.start(); // 调用系统相机拍照并保存图片、展示图片 findViewById(R.id.takephotos).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 调用系统相机 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent,1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == Activity.RESULT_OK){ Bundle bundle = (Bundle)data.getExtras(); Bitmap bitmap = (Bitmap)bundle.get("data"); saveImg2SDcard(bitmap,"/systemTakePhone.jpg"); } } private void saveImg2SDcard(Bitmap bitmap,String fileName) { FileOutputStream fos; try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsoluteFile()+fileName); }else{ fos = new FileOutputStream(getFilesDir()+fileName); } bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); iamgeview.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
以上是关于ios 调用writeToFile将图片保存到本地一直失败的解决方案的主要内容,如果未能解决你的问题,请参考以下文章
iOS writeToFile 保存文件到沙盒某目录失败的解决方案