Você está na página 1de 3

//Esse codigo basicamente pega byte a byte do arquivo e o armazena numa matriz que

vai ser posteriormente copiada para o arquivo que vai ser a copia
//CLASSE MAIN PRA CARREGAR O CODIGO
package testes;

import java.io.IOException;

/**
*
* @author Java
*/
public class Testes {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Eoq j= new Eoq();

j.CarregaPMG("C:\\Users\\Java\\Desktop\\PRJ01\\images\\pepper.ascii.pgm");//mude
isso com o caminho da imagem a ser copiada

j.escrevePMG("C:\\Users\\Java\\Desktop\\PRJ01\\images\\venus2.ascii.pgm");//mude
isso com o caminho do arquivo que vai ser o resultado da copia
}

}
//CLASSE COM OS METODOS

package testes;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Eoq {

int altura,largura,max;
int TAMANHO=700;//Variavel que guarda um tamanho padrao pra matriz que vai ser
responsavel por guardar os caracteres do arquivo
byte imagem[][]= null;
byte b;
public void CarregaPMG(String caminho) throws FileNotFoundException,
IOException{
FileInputStream f = new FileInputStream(caminho);
BufferedReader d = new BufferedReader(new InputStreamReader(f));
String magic = d.readLine();//P2
String line = d.readLine();//Width e height
while (line.startsWith("#")) {//para descartar o comentario*
line = d.readLine();
}

Scanner s = new Scanner(line);


largura = s.nextInt();
altura = s.nextInt();

line=d.readLine();//Valor intensidade mxima na terceira linha


Scanner m= new Scanner(line);
max=m.nextInt();

this.imagem= new byte[TAMANHO][TAMANHO];//aloca a matriz para guardar


os caracteres

for(int i=0;i<TAMANHO;i++){
for(int j=0;j<TAMANHO;j++){
//percorrendo a matriz e a preenchendo com os caracteres lidos do texto
b=(byte) d.read();

imagem[i][j]=b;
if(imagem[i][j]==-1){
break;
}

}
}

f.close();
}
public void escrevePMG(String caminho) throws IOException{

try (BufferedWriter bw = new BufferedWriter(new


FileWriter(caminho))){

//escreve os elementos padroes do arquivo


bw.write("P2\n");

bw.append(largura+" "+altura+"\n");

bw.append(max+"\n");

int i = 0;
int j = 0;

for(i=0;i<TAMANHO;i++){
for(j=0;j<TAMANHO;j++){
if(imagem[i][j]==-1){
break;
}
bw.write(imagem[i][j]); //escrevendo cada caractere da matriz no
arquivo

}
}

bw.flush();

// no need to close it.


bw.close();

System.out.println("Done");

} catch (IOException e) {

e.printStackTrace();

}
}

Você também pode gostar