删除库图像后,相机意图摄意图、相机、库图

2023-09-12 00:06:23 作者:那年夏天丶浅浅の笑

我知道这已被要求在许多不同的方式,但我仍似乎无法从默认的文件夹中删除库图像。我将文件保存到SD卡上正确,我可以删除该文件很好,但在该文件夹的摄像头,显示默认库图像文件将不会删除。

我想的图像删除,一旦活动返回因为文件已保存在SD卡上的下 / Coupon2

有什么建议?

 公共无效startCamera(){
    Log.d(ANDRO_CAMERA,在手机上启动摄像头......);

    mManufacturerText =(EditText上)findViewById(R.id.manufacturer);
    。字符串ManufacturerText = mManufacturerText.getText()的toString();
    字符串currentDateTimeString =新的日期()的toString()。

    意向意图=新的意图(MediaStore.ACTION_IM​​AGE_CAPTURE);
    文件FILEDIR =新的文件(Environment.getExternalStorageDirectory()+/ Coupon2);
    filedir.mkdirs();

    档案文件=新的文件(Environment.getExternalStorageDirectory()+/ Coupon2,ManufacturerText + -  test.png);
    outputFileUri = Uri.fromFile(文件);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);

    startActivityForResult(意向,CAMERA_PIC_REQUEST);
}

保护无效onActivityResult(INT申请code,INT结果code,意图数据){
    super.onActivityResult(要求code,因此code,数据);
    如果(要求code == CAMERA_PIC_REQUEST和放大器;&安培;结果code == -1){
        意向意图=新的意图(com.android.camera.action.CROP);
        intent.putExtra(裁剪,真);
        intent.putExtra(规模化,真);

        intent.putExtra(回归数据,假);
        intent.setDataAndType(outputFileUri,图像/ *);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);
        startActivityForResult(意向,CAMERA_CROP_REQUEST);
    }其他 {
        SetImage();
        saveState和();
    }
}
 

解决方案

我的应用程序需要我打电话的意图拍照。照片不能在画廊,而是必须在SD卡上的特定目录。

本来我只是用EXTRA_OUTPUT,但我很快就发现了以下几点:    - 某些设备完全使用它,并跳过画廊。    - 某些设备完全忽略它只有使用画廊。    - 某些设备实在太烂和全尺寸图像保存到画廊,以及缩略图只保存到我想要的位置。 (HTC你知道你是谁......)

所以,我不能一味删除库文件时,我完成了。最后添加的相片可以是或可以不是一个我想删除。另外,我可能要复制文件替换我自己算账。因为我的活动是2000线,与我公司不希望我们所有的code被张贴,我只发布涉及这样的方法。希望这有助于。

另外,我的状态,这是我的第一个Android应用程序。我也不会感到惊讶,如果有一个更好的方式来做到这一点,我只是不知道,但是这是什么工作对我来说!

所以,这里是我的解决方案:

首先,在我的应用方面,我定义一个变量,如下所示:

 公开的ArrayList<字符串> GalleryList =新的ArrayList<字符串>();
 
上海一程序员离职当天删光代码,有公司曾因 一键 缩水5亿

接下来,在我的活动,我定义的方法来获得在画廊的所有照片的列表:

 私人无效FillPhotoList()
{
   //初始化列表!
   app.GalleryList.clear();
   的String []投影= {MediaStore.Images.ImageColumns.DISPLAY_NAME};
   // intialize的URI和光标,以及当前预期大小。
   光标C = NULL;
   乌里U = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
   //
   //查询URI来获取数据路径。仅如果URI是有效的。
   如果(U!= NULL)
   {
      C = managedQuery(U,投影,NULL,NULL,NULL);
   }

   //如果我们发现光标并发现了一个记录(我们也有ID)。
   如果((C = NULL)及!及(c.moveToFirst()))
   {
      做
      {
        每添加到列表中//循环。
        app.GalleryList.add(c.getString(0));
      }
      而(c.moveToNext());
   }
}
 

下面是一个方法返回一个唯一的文件名对我的新形象:

 私人字符串getTempFileString()
{
   //只有一个时间,我们抢这个位置。
   最终的文件路径=新的文件(Environment.getExternalStorageDirectory()
         的getString(getApplicationInfo()labelRes。));
   //
   //如果不存在,我们可以在这里创建它。
   如果(!path.exists())
   {
      path.mkdir();
   }
   //
   返回新的文件(路径,将String.valueOf(System.currentTimeMillis的())+.JPG)getPath()。
}
 

我在我的活动三个变量,对我存储有关当前文件的信息。一个字符串(路径),文件变量和一个URI到该文件中:

 公共静态字符串sFilePath =;
公共静态文件CurrentFile = NULL;
公共静态乌里CurrentUri = NULL;
 

我从来不设置这些直接,我只调用该文件路径的制定者:

 公共无效setsFilePath(字符串值)
{
   //我们刚刚更新了这个值。物业首盘。
   sFilePath =价值;
   //
   //初始化这两个
   CurrentFile = NULL;
   CurrentUri = NULL;
   //
   //如果我们有真实的东西,设置文件和URI。
   如果(!sFilePath.equalsIgnoreCase())
   {
      CurrentFile =新的文件(sFilePath);
      CurrentUri = Uri.fromFile(CurrentFile);
   }
}
 

现在我打电话的意图拍摄照片。

 公共无效startCamera()
{
   意向意图=新的意图(MediaStore.ACTION_IM​​AGE_CAPTURE);
   //指定的输出。这将是唯一的。
   setsFilePath(getTempFileString());
   //
   intent.putExtra(MediaStore.EXTRA_OUTPUT,CurrentUri);
   //
   //保存为事后名单
   FillPhotoList();
   //
   //最后启动的意图,并等待结果。
   startActivityForResult(意向,IMAGE_CAPTURE);
}
 

一旦做到这一点,并且活动回来,这里是我的code:

 保护无效onActivityResult(INT申请code,INT结果code,意图数据)
{
   如果(要求code == IMAGE_CAPTURE)
   {
      //基础上,我们要么设置preVIEW或显示快速敬酒飞溅的结果。
      如果(结果code == RESULT_OK)
      {
         // 这是荒唐的。 Android系统节省一些版本
         //为MediaStore为好。不知道为什么!我们不知道是什么
         //名字Android将放弃要么,所以我们得到搜索此
         //手动将其取出。
         的String []投影= {MediaStore.Images.ImageColumns.SIZE,
                                 MediaStore.Images.ImageColumns.DISPLAY_NAME,
                                 MediaStore.Images.ImageColumns.DATA,
                                 BaseColumns._ID,};
         //
         // intialize的URI和光标,以及当前预期大小。
         光标C = NULL;
         乌里U = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
         //
         如果(CurrentFile!= NULL)
         {
            //查询URI来获取数据路径。仅如果URI是有效的,
            //我们有一个有效的大小来寻找。
            如果((U = NULL)及!及(CurrentFile.length()0))
            {
               C = managedQuery(U,投影,NULL,NULL,NULL);
            }
            //
            //如果我们发现光标并发现了一个记录(我们也有大小)。
            如果((C = NULL)及!及(c.moveToFirst()))
            {
               做
               {
                  //检查我们以前建造的GALLARY每个区域。
                  布尔bFound = FALSE;
                  对于(字符串sGallery:app.GalleryList)
                  {
                     如果(sGallery.equalsIgnoreCase(c.getString(1)))
                     {
                        bFound = TRUE;
                        打破;
                     }
                  }
                  //
                  //这里,我们循环完整的画廊。
                  如果(!bFound)
                  {
                     //这是新的形象。如果尺寸较大,将其复制。
                     //然后将其删除!
                     文件F =新的文件(c.getString(2));

                     //确保它的存在,检查大小和删除!
                     如果((f.exists())及及(CurrentFile.length()&其中; c.getLong(0))及及(CurrentFile.delete()))
                     {
                        //最后,我们可以停止复制。
                        尝试
                        {
                           CurrentFile.createNewFile();
                           FileChannel源= NULL;
                           FileChannel目标= NULL;
                           尝试
                           {
                              来源=新的FileInputStream(F).getChannel();
                              目标=新的FileOutputStream(CurrentFile).getChannel();
                              destination.transferFrom(源,0,source.size());
                           }
                           最后
                           {
                              如果(来源!= NULL)
                              {
                                 source.close();
                              }
                              如果(目标!= NULL)
                              {
                                 destination.close();
                              }
                           }
                        }
                        赶上(IOException异常E)
                        {
                           //无法复制的文件覆盖。
                           app.CallToast(PhotosActivity.this,的getString(R.string.ErrorOccured),0);
                        }
                     }
                     //
                     ContentResolver的CR = getContentResolver();
                     cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        BaseColumns._ID +=+ c.getString(3),空);
                     打破;
                  }
               }
               而(c.moveToNext());
            }
         }
      }
   }
}
 

I know this has been asked in many different ways but I still can not seem to delete the gallery image from the default folder. I'm saving the file to the SD card correctly and I can delete that file fine, but the default gallery image file that shows under the folder Camera will not delete.

I would like the image to delete once the activity is returned since the file is already stored on the SD card under /Coupon2.

Any suggestions?

public void startCamera() {
    Log.d("ANDRO_CAMERA", "Starting camera on the phone...");

    mManufacturerText = (EditText) findViewById(R.id.manufacturer);
    String ManufacturerText = mManufacturerText.getText().toString();
    String currentDateTimeString = new Date().toString();

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File filedir = new File(Environment.getExternalStorageDirectory()+"/Coupon2");
    filedir.mkdirs();

    File file = new File(Environment.getExternalStorageDirectory()+"/Coupon2", ManufacturerText+"-test.png");
    outputFileUri = Uri.fromFile(file);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

    startActivityForResult(intent, CAMERA_PIC_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_PIC_REQUEST && resultCode == -1) {  
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", "true");

        intent.putExtra("return-data", false);
        intent.setDataAndType(outputFileUri, "image/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(intent, CAMERA_CROP_REQUEST);
    }else { 
        SetImage();
        saveState();
    }
}

解决方案

My application requires me to call an intent to take a photo. The photo cannot be in the gallery but instead must be in a specific directory on the SD card.

Originally I just used the EXTRA_OUTPUT, but I soon discovered the following: - Some devices use it completely and skip the gallery. - Some devices ignore it completely and ONLY use the gallery. - Some devices really suck and save a full sized image to the gallery, and save a thumbnail only to the location I wanted. (HTC you know who you are...)

So, I can't blindly delete a gallery file when I'm done. The last added photo may or may not be the one I want to remove. Also, I may have to copy that file replacing my own afterwards. Because my activity is 2000 lines, and my company wouldn't want all of our code being posted, I'm posting only the methods involved in doing this. Hopefully this helps.

Also, I'll state, this is my first Android application. I wouldn't be surprised if there was a better way to do this that I just don't know about, but this is what's working for me!

So, here is my solution:

First, in my application context I define a variable as follows:

public ArrayList<String> GalleryList = new ArrayList<String>();

Next, in my activity, I define a method to get a list of all photos in the gallery:

private void FillPhotoList()
{
   // initialize the list!
   app.GalleryList.clear();
   String[] projection = { MediaStore.Images.ImageColumns.DISPLAY_NAME };
   // intialize the Uri and the Cursor, and the current expected size.
   Cursor c = null; 
   Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
   //
   // Query the Uri to get the data path.  Only if the Uri is valid.
   if (u != null)
   {
      c = managedQuery(u, projection, null, null, null);
   }

   // If we found the cursor and found a record in it (we also have the id).
   if ((c != null) && (c.moveToFirst())) 
   {
      do 
      {
        // Loop each and add to the list.
        app.GalleryList.add(c.getString(0));
      }     
      while (c.moveToNext());
   }
}

Here's a method to return a unique file name for my new image:

private String getTempFileString()
{
   // Only one time will we grab this location.
   final File path = new File(Environment.getExternalStorageDirectory(), 
         getString(getApplicationInfo().labelRes));
   //
   // If this does not exist, we can create it here.
   if (!path.exists())
   {
      path.mkdir();
   }
   //
   return new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg").getPath();
}

I have three variables in my Activity that store information for me about a current file. A string (path), a File variable, and a URI to that file:

public static String sFilePath = ""; 
public static File CurrentFile = null;
public static Uri CurrentUri = null;

I never set these directly, I only call a setter on the file path:

public void setsFilePath(String value)
{
   // We just updated this value. Set the property first.
   sFilePath = value;
   //
   // initialize these two
   CurrentFile = null;
   CurrentUri = null;
   //
   // If we have something real, setup the file and the Uri.
   if (!sFilePath.equalsIgnoreCase(""))
   {
      CurrentFile = new File(sFilePath);
      CurrentUri = Uri.fromFile(CurrentFile);
   }
}

Now I call an intent to take a photo.

public void startCamera()
{
   Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
   // Specify the output. This will be unique.
   setsFilePath(getTempFileString());
   //
   intent.putExtra(MediaStore.EXTRA_OUTPUT, CurrentUri);
   //
   // Keep a list for afterwards
   FillPhotoList();
   //
   // finally start the intent and wait for a result.
   startActivityForResult(intent, IMAGE_CAPTURE);
}

Once this is done, and the activity comes back, here is my code:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
   if (requestCode == IMAGE_CAPTURE)
   {
      // based on the result we either set the preview or show a quick toast splash.
      if (resultCode == RESULT_OK)
      {
         // This is ##### ridiculous.  Some versions of Android save
         // to the MediaStore as well.  Not sure why!  We don't know what
         // name Android will give either, so we get to search for this
         // manually and remove it.  
         String[] projection = { MediaStore.Images.ImageColumns.SIZE,
                                 MediaStore.Images.ImageColumns.DISPLAY_NAME,
                                 MediaStore.Images.ImageColumns.DATA,
                                 BaseColumns._ID,};
         //    
         // intialize the Uri and the Cursor, and the current expected size.
         Cursor c = null; 
         Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
         //
         if (CurrentFile != null)
         {               
            // Query the Uri to get the data path.  Only if the Uri is valid,
            // and we had a valid size to be searching for.
            if ((u != null) && (CurrentFile.length() > 0))
            {
               c = managedQuery(u, projection, null, null, null);
            }
            //   
            // If we found the cursor and found a record in it (we also have the size).
            if ((c != null) && (c.moveToFirst())) 
            {
               do 
               {
                  // Check each area in the gallary we built before.
                  boolean bFound = false;
                  for (String sGallery : app.GalleryList)
                  {
                     if (sGallery.equalsIgnoreCase(c.getString(1)))
                     {
                        bFound = true;
                        break;
                     }
                  }
                  //       
                  // To here we looped the full gallery.
                  if (!bFound)
                  {
                     // This is the NEW image.  If the size is bigger, copy it.
                     // Then delete it!
                     File f = new File(c.getString(2));

                     // Ensure it's there, check size, and delete!
                     if ((f.exists()) && (CurrentFile.length() < c.getLong(0)) && (CurrentFile.delete()))
                     {
                        // Finally we can stop the copy.
                        try
                        {
                           CurrentFile.createNewFile();
                           FileChannel source = null;
                           FileChannel destination = null;
                           try 
                           {
                              source = new FileInputStream(f).getChannel();
                              destination = new FileOutputStream(CurrentFile).getChannel();
                              destination.transferFrom(source, 0, source.size());
                           }
                           finally 
                           {
                              if (source != null) 
                              {
                                 source.close();
                              }
                              if (destination != null) 
                              {
                                 destination.close();
                              }
                           }
                        }
                        catch (IOException e)
                        {
                           // Could not copy the file over.
                           app.CallToast(PhotosActivity.this, getString(R.string.ErrorOccured), 0);
                        }
                     }
                     //       
                     ContentResolver cr = getContentResolver();
                     cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                        BaseColumns._ID + "=" + c.getString(3), null);
                     break;                        
                  }
               } 
               while (c.moveToNext());
            }
         }
      }
   }      
}