2017-10-03 7 views
1

フラグメントを作成してデバイスに保存します。しかし、私はデバイスの内部storage.Iにファイルを保存する方法を理解していない私は例外 "FileNotFoundException電子"私はプログラムを試してみる。フラグメントを画像ファイルにして、それを電話機の内蔵ハードドライブに保存します。

Button save = (Button) findViewById(R.id.save); 
     save.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       View fragment = (View) findViewById(R.id.fragment2); 
       viewToBitmap(fragment); 
      } 
     } 
     ); 
    } 

    public Bitmap viewToBitmap(View view) { 
     Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); 
     Canvas canvas = new Canvas(bitmap); 
     view.draw(canvas); 
     try { 
      FileOutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png"); 

      bitmap.compress(Bitmap.CompressFormat.PNG, 100, output); 
      output.close(); 
     } catch (FileNotFoundException e) { 
      Toast.makeText(this, "Error1", Toast.LENGTH_SHORT).show(); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      Toast.makeText(this, "Error2", Toast.LENGTH_SHORT).show(); 
      e.printStackTrace(); 
     } 
     return bitmap; 
    } 

答えて

0

FileOutputStreamを作成していますが、その前にファイルを作成していません。そのファイルに出力ストリームを書き込む前に、FileFolderとFileを作成する必要があります。あなたの方法のために以下のコードを修正しましたviewToBitmap

public Bitmap viewToBitmap(View view) { 
       Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); 
       Canvas canvas = new Canvas(bitmap); 
       view.draw(canvas); 
       try { 
       File tempFolder = new File(Environment.getExternalStorageDirectory() + "/path/to"); 
       if (!tempFolder.exists()) tempFolder.mkdirs(); 
       File tempFile = File.createTempFile("tempFile", ".jpg", tempFolder); 
         FileOutputStream output = new FileOutputStream(tempFile); 
         bitmap.compress(Bitmap.CompressFormat.PNG, 100, output); 
         output.close(); 
       } catch (FileNotFoundException e) { 
        Toast.makeText(this, "Error1", Toast.LENGTH_SHORT).show(); 
        e.printStackTrace(); 
       } catch (IOException e) { 
        Toast.makeText(this, "Error2", Toast.LENGTH_SHORT).show(); 
        e.printStackTrace(); 
       } 
       return bitmap; 
      } 
関連する問題