Android-创建自己的文件夹以保存相机拍摄的图像
我可以制作自己的文件夹来保存相机拍摄的照片吗。我已经在我的代码和图片保存到sdcard0,但名称始终是临时的,如果我采取其他照片,它的工作。有人能帮我吗 这里是我的MainActivity.javaAndroid-创建自己的文件夹以保存相机拍摄的图像,android,android-intent,camera,android-camera,mkdir,Android,Android Intent,Camera,Android Camera,Mkdir,我可以制作自己的文件夹来保存相机拍摄的照片吗。我已经在我的代码和图片保存到sdcard0,但名称始终是临时的,如果我采取其他照片,它的工作。有人能帮我吗 这里是我的MainActivity.java public class MainActivity extends Activity implements OnClickListener{ private EditText nama, harga, kondisi, notelepon; private TextView messageTex
public class MainActivity extends Activity implements OnClickListener{
private EditText nama, harga, kondisi, notelepon;
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
nama = (EditText)findViewById(R.id.nama_barang);
harga = (EditText)findViewById(R.id.harga_barang);
kondisi = (EditText)findViewById(R.id.kondisi_barang);
notelepon = (EditText)findViewById(R.id.no_telepon);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://192.168.43.226/jualan/barang_tes/UploadToServer.php";
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
imagepath = f.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
//send();
}
}).start();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
// bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
imageview.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
imagepath = getPath(selectedImage);
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
//Log.w("path of image from gallery......******************.........", picturePath+"");
imageview.setImageBitmap(thumbnail);
messageText.setText("Uploading file path:" +imagepath);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
String nm = nama.getText().toString();
String hrg = harga.getText().toString();
String knds = kondisi.getText().toString();
String notlp = notelepon.getText().toString();
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
conn.setRequestProperty("uploaded_nama", nm);
conn.setRequestProperty("uploaded_harga", hrg);
conn.setRequestProperty("uploaded_kondisi", knds);
conn.setRequestProperty("uploaded_notelepon", notlp);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_nama" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
dos.writeBytes(lineEnd);
dos.writeBytes(nm); // nm is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_harga" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
dos.writeBytes(lineEnd);
dos.writeBytes(hrg); // nm is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_kondisi" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
dos.writeBytes(lineEnd);
dos.writeBytes(knds); // nm is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_notelepon" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
dos.writeBytes(lineEnd);
dos.writeBytes(notlp); // nm is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" C:/AppServ/www/kambing/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
//Intent i = new Intent(MainActivity.this,InputInfo.class);
finish();
//startActivity(i);
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
使用以下方法创建或获取(如果已存在)您的目录: (摘自) 以及以下实现文件复制的方法:(从: ) 最后,在您的
onActivityResult
方法中,使用以下代码行将临时文件从相机复制到更持久的位置:
File picturesDir = getAlbumStorageDir(this, "myDirName");
File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic.jpg");
try {
copy(temp, savedPic);
} catch (IOException e) {
Log.e("MainActivity.err", "failed to copy");
}
另一个提示。似乎为了获得从相机拍摄的照片,您正在迭代图片目录中的所有图片,以找到名为temp.jpg的图片。这是一种非常糟糕的做法,因为当目录中有很多图片时,速度可能会非常慢,更糟糕的是,在android的未来版本(或更早版本)上,文件名可能不是temp或不在该文件夹中。
相反,请按照此问题中的答案查找获取临时图片路径的正确且更有效的方法:使用以下方法创建或获取(如果已经存在)您的目录: (摘自) 以及以下实现文件复制的方法:(从: ) 最后,在您的
onActivityResult
方法中,使用以下代码行将临时文件从相机复制到更持久的位置:
File picturesDir = getAlbumStorageDir(this, "myDirName");
File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic.jpg");
try {
copy(temp, savedPic);
} catch (IOException e) {
Log.e("MainActivity.err", "failed to copy");
}
另一个提示。似乎为了获得从相机拍摄的照片,您正在迭代图片目录中的所有图片,以找到名为temp.jpg的图片。这是一种非常糟糕的做法,因为当目录中有很多图片时,速度可能会非常慢,更糟糕的是,在android的未来版本(或更早版本)上,文件名可能不是temp或不在该文件夹中。 相反,请按照此问题中的答案查找获取临时图片路径的正确且更有效的方法:如何创建文件夹
// make a folder with name PicturesNR2
String RootDir = Environment.getExternalStorageDirectory() + File.separator + "PicturesNR2";
File RootFile = new File(RootDir);
RootFile.mkdir();
如何检索文件
// here picname is with extension
File imageFile = new File("/sdcard/PicturesNR2/"+picname);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
还要添加到清单文件中
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后在“活动结果”方法的代码中
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
// bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
imageview.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
把这个换成这个
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
// create folder first
createFolder();
// get the photo from intent
Bitmap photo = (Bitmap) data.getExtras().get("data");
// set the bitmap to imageview
imageview.setImageBitmap(photo);
// this code is use to generate random number and add to file
// name so that each file should be different
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
// set the file path
// sdcard/PictureFolder/ is the folder created in create folder method
String filePath = "/sdcard/PictureFolder/"+fname;
// the rest of the code is for saving the file to filepath mentioned above
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
photo.compress(CompressFormat.PNG, 100, bos);
try {
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (requestCode == 2) {.........
我已经在我的手机上测试了这段代码,它运行良好如何创建文件夹
// make a folder with name PicturesNR2
String RootDir = Environment.getExternalStorageDirectory() + File.separator + "PicturesNR2";
File RootFile = new File(RootDir);
RootFile.mkdir();
如何检索文件
// here picname is with extension
File imageFile = new File("/sdcard/PicturesNR2/"+picname);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
还要添加到清单文件中
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后在“活动结果”方法的代码中
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
// bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
imageview.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
把这个换成这个
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
// create folder first
createFolder();
// get the photo from intent
Bitmap photo = (Bitmap) data.getExtras().get("data");
// set the bitmap to imageview
imageview.setImageBitmap(photo);
// this code is use to generate random number and add to file
// name so that each file should be different
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
// set the file path
// sdcard/PictureFolder/ is the folder created in create folder method
String filePath = "/sdcard/PictureFolder/"+fname;
// the rest of the code is for saving the file to filepath mentioned above
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
photo.compress(CompressFormat.PNG, 100, bos);
try {
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (requestCode == 2) {.........
我已在手机上测试了此代码,效果良好如果要将图片存储在SD卡的图片目录中,请执行以下操作:
private static File createPictureDirectory()
{
File sdDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDirectory, "mypictures");
}
这将创建并返回名为mypictures的文件夹,然后您可以通过写入该文件夹将照片存储在该文件夹中。在存储照片之前,请始终记住在android清单文件中请求写入权限
我希望这有帮助。如果您想将图片存储在SD卡的图片目录中,请执行以下操作:
private static File createPictureDirectory()
{
File sdDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDirectory, "mypictures");
}
这将创建并返回名为mypictures的文件夹,然后您可以通过写入该文件夹将照片存储在该文件夹中。在存储照片之前,请始终记住在android清单文件中请求写入权限
我希望这能有所帮助。您能进一步解释您的问题吗?代码的哪一部分不起作用?这是什么意思?能否在代码段中添加指向问题所在部分的注释?或者至少描述一下每个函数应该做什么?这将大大有助于理解问题所在。@Tom我的代码正在运行。但我需要制作自己的文件夹来保存相机拍摄的照片。我不知道该怎么做。你能帮我吗?@看不出我如何创造的答案folder@SoftCoder你能告诉我如何在我的代码中实现它吗?@看不到我编辑过的答案你能进一步解释你的问题吗?代码的哪一部分不起作用?这是什么意思?能否在代码段中添加指向问题所在部分的注释?或者至少描述一下每个函数应该做什么?这将大大有助于理解问题所在。@Tom我的代码正在运行。但我需要制作自己的文件夹来保存相机拍摄的照片。我不知道该怎么做。你能帮我吗?@看不出我如何创造的答案folder@SoftCoder你能告诉我如何在我的代码中实现它吗?@看不到我编辑的答案我已经编辑了我的答案。。忘记添加imageview.setImageBitmap(照片);现在添加了:)我已经编辑了我的答案。。忘记添加imageview.setImageBitmap(照片);现在添加了:)我很确定您可以在
main活动
中将上面的两个代码片段作为私有方法复制过去,然后在onActivityResponse
中的for循环下复制第三个。尽管如此,请参阅我答案中关于for循环的PS。再看一眼,您可能需要更改我使用的变量名称以适合您使用的名称。我认为我的temp
应该是你的f
我很确定你可以在MainActivity
中将上面的两个代码片段作为私有方法复制过去,然后在你的onActivityResponse
的for循环下面复制第三个。尽管如此,请参阅我答案中关于for循环的PS。再看一眼,您可能需要更改我使用的变量名称以适合您使用的名称。我想我的temp
应该是你的f