Android开发帮助:保存图像从RES /生或资产文件夹在SD卡 [英] Android Dev Help: Saving an image from Res/raw or Asset folder to the Sd card

查看:137
本文介绍了Android开发帮助:保存图像从RES /生或资产文件夹在SD卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从RES /生或资产文件夹复制到SD卡的位置(/ SD卡/ DCIM /).

保存图像(JPG或PNG)

我一直在下面的教程,可以保存图像从URL到SD卡根目录,但我已经到处是能够挽救RES /生或资产的文件夹,而是和一个目前存在的位置onthe SD卡/ SD卡/ DCIM /

下面是code,谁能告诉我怎么做上面的呢?

 公共类家庭延伸活动{
    私人文件的文件;
     私人字符串imgNumber;
     私人按钮btnDownload;
     / **第一次创建活动时调用。 * /
        @覆盖
        公共无效的onCreate(包savedInstanceState){
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.main);
       btnDownload =(按钮)findViewById(R.id.btnDownload);

      btnDownload.setOnClickListener(新OnClickListener(){

     公共无效的onClick(视图v){
       btnDownload.setText(下载正在进行中。);
      字符串savedFilePath =下载(http://www.domain.com/android1.png);
      Toast.makeText(getApplicationContext(),文件被保存在+ savedFilePath,1000).show();
      如果(savedFilePath!= NULL)
      {
        btnDownload.setText(下载完成。);
      }
     }
    });

    }
    公共字符串下载(字符串URL)
    {
    字符串的文件路径= NULL;
    尝试 {
    //设置下载网址,网址指向的文件在互联网上
    //这是要下载的文件
    网址URL =新的URL(网址);
    //创建新的连接
    HttpURLConnection的的URLConnection =(HttpURLConnection类)url.openConnection();

    //设置一些东西的连接
    urlConnection.setRequestMethod(GET);
    urlConnection.setDoOutput(真正的);
    //并连接!
    urlConnection.connect();
    //设置的路径,我们要保存文件
    //在这种情况下,将其保存在的根目录
    //SD卡。
    文件SDCardRoot = Environment.getExternalStorageDirectory();
    //创建一个新的文件,指定路径和文件名
    //这是我们要保存的文件。

    字符串文件名=下载_+ System.currentTimeMillis的()+巴。 //你可以下载到任何类型的文件,例如:.JPEG(图像),.TXT(文本文件),. MP3(音频文件)
    Log.i(本地文件名:,+文件名);
    文件=新的文件(SDCardRoot,文件名);
    如果(file.createNewFile())
    {
    file.createNewFile();
    }

    //这将被用于所下载的数据写入到我们创建的文件
    FileOutputStream中fileOutput =新的FileOutputStream(文件);

    //这将在从互联网读取数据被用于
    InputStream中的InputStream = urlConnection.getInputStream();

    //这是文件的总大小
    INT totalSize = urlConnection.getContentLength();
    //变量来存储下载的总字节
    INT downloadedSize = 0;

    //创建一个缓冲区...
    byte []的缓冲区=新的字节[1024];
    INT BufferLength中= 0; //用于存储缓冲器的临时尺寸

    //现在,读取通过输入缓冲器和将内容写入到该文件
    而(量(bufferLength = inputStream.read(缓冲液))大于0){
    //在缓冲器的数据添加到该文件中的文件输出流(该文件的SD卡上
    fileOutput.write(缓冲液,0,BufferLength中);
    //加起来的规模,所以我们知道有多少下载
    downloadedSize + = BufferLength中;
    //这是在那里你会做一些报告prgress,这样也许
    Log.i(进步,downloadedSize:+ downloadedSize +totalSize:+ totalSize);
    btnDownload.setText(下载状态:+ downloadedSize +/+ totalSize);
    }
    完成后//关闭输出流
    fileOutput.close();
    如果(downloadedSize == totalSize)文件路径= file.getPath();

    //捕捉一些可能出现的错误?
    }赶上(MalformedURLException异常E){
    e.printStackTrace();
    }赶上(IOException异常E){
    文件路径= NULL;

    btnDownload.setText(网络连接失败\ñ。+ e.getMessage());
    e.printStackTrace();
    }
    Log.i(文件路径:,+文件路径);
    返回文件路径;

    }

}
 

解决方案

测试和工作code:

为了从资源(image1.png)图像复制到SD卡上,你可以试试下面的办法的图片目录(image1.jpg)图像文件(android.permission.WRITE_EXTERNAL_STORAG​​E需要保存图像的SD卡)。 ACTION_MEDIA_SCANNER_SCAN_FILE广播已发送,以通过新的图像媒体扫描仪,所以这将是可见的媒体库的ASAP。

 进口java.io.ByteArrayOutputStream中;
进口的java.io.File;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口java.io.OutputStream中;
进口android.net.Uri;
进口android.app.Activity;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.widget.Button;
进口android.os.Bundle;
进口android.os.Environment;
进口android.view.View

公共类MainScreen扩展活动
{
    私人按钮btnDownload;
    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        btnDownload =(按钮)findViewById(R.id.SaveButton1);

        btnDownload.setOnClickListener(
            新Button.OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){
                    串newPicture = saveToSDCard(R.drawable.image1image1.jpg);
                    startMediaScanner(newPicture);
                }
            }
        );
    }

    私人字符串saveToSDCard(INT RESOURCEID,串finalName)
    {
        StringBuffer的createdFile =新的StringBuffer();

        位图resourceImage = BitmapFactory.de codeResource(this.getResources(),RESOURCEID);
        文件externalStorageFile =新的文件(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),finalName);
        ByteArrayOutputStream字节=新ByteArrayOutputStream();
        resourceImage.com preSS(Bitmap.Com pressFormat.JPEG,100个字节);
        BYTE B [] = bytes.toByteArray();

        尝试
        {
            externalStorageFile.createNewFile();
            的OutputStream filoutputStream =新的FileOutputStream(externalStorageFile);
            filoutputStream.write(B);
            filoutputStream.flush();
            filoutputStream.close();
            createdFile.append(externalStorageFile.getAbsolutePath());
        }
        赶上(IOException异常E)
        {
        }

        返回createdFile.toString();
    }

    私人无效startMediaScanner(字符串addedPicture)
    {
         sendBroadcast(新意图(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.parse(文件://+ addedPicture)));
    }
}
 

I am trying to save an image (jpg or png) from the res/raw or assets folder to the SD card location (/sdcard/DCIM/).

I have been following a tutorial which can save an image from a URL to the SD card Root, but i have looked everywhere to be able to save from res/raw or asset folder instead, and to a differnet location onthe sd card /sdcard/DCIM/

Here is the code, can anyone show me how to do the above from this?

public class home extends Activity {
    private File file;
     private String imgNumber;
     private Button btnDownload;
     /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main); 
       btnDownload=(Button)findViewById(R.id.btnDownload);

      btnDownload.setOnClickListener(new OnClickListener() {

     public void onClick(View v) {
       btnDownload.setText("Download is in Progress.");
      String savedFilePath=Download("http://www.domain.com/android1.png");
      Toast.makeText(getApplicationContext(), "File is Saved in  "+savedFilePath, 1000).show();
      if(savedFilePath!=null)
      {
        btnDownload.setText("Download Completed.");
      }
     }
    });

    } 
    public String Download(String Url)
    {
    String filepath=null;
    try {
    //set the download URL, a url that points to a file on the internet
    //this is the file to be downloaded
    URL url = new URL(Url);
    //create the new connection
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    //set up some things on the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
    //and connect!
    urlConnection.connect();
    //set the path where we want to save the file
    //in this case, going to save it on the root directory of the
    //sd card.
    File SDCardRoot = Environment.getExternalStorageDirectory();
    //create a new file, specifying the path, and the filename
    //which we want to save the file as.

    String filename= "download_"+System.currentTimeMillis()+".png";   // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
    Log.i("Local filename:",""+filename);
    file = new File(SDCardRoot,filename);
    if(file.createNewFile())
    {
    file.createNewFile();
    }

    //this will be used to write the downloaded data into the file we created
    FileOutputStream fileOutput = new FileOutputStream(file);

    //this will be used in reading the data from the internet
    InputStream inputStream = urlConnection.getInputStream();

    //this is the total size of the file
    int totalSize = urlConnection.getContentLength();
    //variable to store total downloaded bytes
    int downloadedSize = 0;

    //create a buffer...
    byte[] buffer = new byte[1024];
    int bufferLength = 0; //used to store a temporary size of the buffer

    //now, read through the input buffer and write the contents to the file
    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
    //add the data in the buffer to the file in the file output stream (the file on the sd card
    fileOutput.write(buffer, 0, bufferLength);
    //add up the size so we know how much is downloaded
    downloadedSize += bufferLength;
    //this is where you would do something to report the prgress, like this maybe
    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
    btnDownload.setText("download Status:"+downloadedSize+" / "+totalSize);
    }
    //close the output stream when done
    fileOutput.close();
    if(downloadedSize==totalSize) filepath=file.getPath();

    //catch some possible errors...
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    filepath=null;

    btnDownload.setText("Internet Connection Failed.\n"+e.getMessage());
    e.printStackTrace();
    }
    Log.i("filepath:"," "+filepath) ; 
    return filepath;

    }

}

解决方案

Tested and working code:

In order to copy image from resources (image1.png) to the image file in the Pictures directory (image1.jpg) on SD card you can try the following approach (android.permission.WRITE_EXTERNAL_STORAGE needed for saving image on the SD card). ACTION_MEDIA_SCANNER_SCAN_FILE broadcast has been sent in order to pass new picture to the media scanner, so it would be visible in the Media Gallery ASAP.

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.net.Uri;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Button;
import android.os.Bundle;
import android.os.Environment;
import android.view.View

public class MainScreen extends Activity 
{ 
    private Button btnDownload;
    /** Called when the activity is first created. */
    @Override     
    public void onCreate(Bundle savedInstanceState) 
    {         
        super.onCreate(savedInstanceState);         
        setContentView(R.layout.main);     
        btnDownload=(Button)findViewById(R.id.SaveButton1);

        btnDownload.setOnClickListener(
            new Button.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String newPicture = saveToSDCard(R.drawable.image1, "image1.jpg");
                    startMediaScanner(newPicture);
                }
            }
        );
    }

    private String saveToSDCard(int resourceID, String finalName)
    {
        StringBuffer createdFile = new StringBuffer();

        Bitmap resourceImage = BitmapFactory.decodeResource(this.getResources(), resourceID);       
        File externalStorageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), finalName);
        ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
        resourceImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        byte b[] = bytes.toByteArray(); 

        try 
        {
            externalStorageFile.createNewFile(); 
            OutputStream filoutputStream = new FileOutputStream(externalStorageFile); 
            filoutputStream.write(b); 
            filoutputStream.flush(); 
            filoutputStream.close();
            createdFile.append(externalStorageFile.getAbsolutePath());
        }
        catch (IOException e)
        {
        }

        return createdFile.toString();
    }

    private void startMediaScanner(String addedPicture)
    {
         sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ addedPicture)));
    }
}

这篇关于Android开发帮助:保存图像从RES /生或资产文件夹在SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆