2013-05-04 68 views
1

我已經創建了一個android應用程序,它將捕獲圖片並保存在sdcard文件夾中,現在我想用自定義名稱保存圖像。在android中用相機捕獲圖像並保存爲自定義名稱

import java.io.ByteArrayOutputStream; 
import android.view.Menu; 
import android.app.Activity; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 

public class MainActivity extends Activity { 

    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     this.imageView = (ImageView) this.findViewById(R.id.imageView1); 
     Button photoButton = (Button) this.findViewById(R.id.button1); 

     photoButton.setOnClickListener(new View.OnClickListener() 
     { 

      @Override 
      public void onClick(View v) 
      { 

       Intent cameraIntent = new Intent(
         android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
         MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath()); 
       cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "new-photo-name.jpg"); 
       startActivityForResult(cameraIntent, CAMERA_REQUEST); 
      } 
     }); 
    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) 
     { 
      Bitmap photo = (Bitmap) data.getExtras().get("data"); 
      imageView.setImageBitmap(photo); 
      MediaStore.Images.Media.insertImage(getContentResolver(), photo, 
        null, null); 

      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      photo.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
      byte[] b = baos.toByteArray(); 

     } 
    } 

這裏是我已經用於捕捉圖像,並將它們保存在SD卡文件夾中的代碼,請幫我保存圖像與如特定名稱:android.jpeg

+1

http://stackoverflow.com/questions/5430527/how-to-launch-the-camera-and-take-a-picture。已經搜索過嗎? – Raghunandan 2013-05-04 13:23:26

+0

你想爲保存的圖片指定一個通用名稱嗎? – kabuto178 2013-05-04 13:28:49

+0

我想用一個特定的名稱保存圖片名稱,例如:android.jpeg – coolboy 2013-05-04 13:32:50

回答

1
File outFile = new File(Environment.getExternalStorageDirectory(), "myname.jpeg"); 
FileOutputStream fos = new FileOutputStream(outFile); 
photo.compress(Bitmap.CompressFormat.JPEG, 100, fos); 
fos.flush(); 
fos.close(); 

您還需要在Android Manifest中添加權限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

的片段將節省的photo/sdcard內容與名稱"myname.jpeg"

+1

謝謝,這一個工作:) – coolboy 2013-05-04 15:40:45

0

你需要把文件名作爲意向額外 -

cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "android.jpg"); 
+0

我已經嘗試過,但沒有工作。 – coolboy 2013-05-04 13:40:24

0

this文章也許有用,試試吧。

& this以及他使用日期作爲默認名稱的唯一不同。 改變它。

它通常工作:)

相關問題