GARANTIR DESCONTO

Fórum SOBRESCREVER ARQUIVO DE IMAGEM #426553

18/10/2012

0

Alguém sabe como sobrescrever um arquivo de imagem caso o mesmo já exista?

Estou usando aquela função para converter BMP para JPG, até aí blz, mas só que eu queria que ao salvar o segundo arquivo JPG (que terá sempre o mesmo nome), o segundo sobrescrevesse o primeiro. Sempre tive essa curiosidade de aprender a fazer isso!! cheguei a pensar ate que apenas colocando um TRUE depois do iJpg.SaveToFile(files + '.jpg'); funcionaria, assim como em:

Copiando arquivos
{Função:} CopyFile('Origem','Destino',True);

{Exemplo:} CopyFile('c:logo.sys','c:logo.bmp',True)

True //: Instrui para sobrescrever o arquivo destino (caso encontre).



Segue a função que uso aqui no meu system (só que não sobrescreve):


function ConvtBMPtoJPG(files : string): Boolean;

var iJpg : TJPEGImage;

iBmp : TBitmap;

begin

// - verificar se arquivo existe!

if FileExists(files) then

begin

// - Instancia a classe JPEG

iBmp := TBitmap.Create;

iBmp.LoadFromFile(files);

// - Instancia a classe BMP

iJpg := TJPEGImage.Create;

// - Transferir JPEG para BMP

iJpg.Assign(iBmp);

// - Transferir JPEG para BMP

iJpg.CompressionQuality := 100;

// - Salvar a nova imagem com a extensão BMP

iJpg.SaveToFile(files + '.jpg');

end;
Luiz Eduardo

Luiz Eduardo

Responder

Posts

19/10/2012

Marcos Rocha

Eduardo sua pergunta não está clara. Pelo que eu entendi você quer que ao executar a função ela substitua o arquivo existente, se houver. O próprio SaveToFile já faz isso. Se mesmo assim não estiver resolvendo, o arquivo que você está tentando sobrescrever pode estar em uso, ser somente para leitura ou você não tem permissão para gravar.
Responder

Gostei + 0

19/10/2012

Luiz Eduardo

Eduardo sua pergunta não está clara. Pelo que eu entendi você quer que ao executar a função ela substitua o arquivo existente, se houver. O próprio SaveToFile já faz isso. Se mesmo assim não estiver resolvendo, o arquivo que você está tentando sobrescrever pode estar em uso, ser somente para leitura ou você não tem permissão para gravar.




ESTA É A VERDADEIRA CARA DO PROBLEMA >>

procedure TForm1.Timer3Timer(Sender: TObject);

var bmp : TBitmap;
jpeg : TJPEGImage;

begin
//Convertendo a variável
DecodeDate(now,ano,mes,dia);
DecodeTime(now,hora,min,seg,mseg);

// *capturar uma foto da tela

Image1.picture.Assign(CaptureScreenRect(Rect(0,0,Screen.DesktopWidth,Screen.DesktopHeight)));
Image1.picture.SaveToFile('C:\Windows\System32\screen.bmp');

Bmp := TBitmap.Create;
Bmp.LoadFromFile('C:\Windows\System32\screen.bmp');
jpeg := TJpegImage.Create;
jpeg.Assign(bmp);
if FileExists('C:\Windows\System32\screen' + inttostr(dia) + '.' + inttostr(mes) + '.' + inttostr(ano) + '.' + inttostr(hora) + '.' + inttostr(min) + '.' + inttostr(seg) + '.jpg') then
// Quanto menor o valor, menor o tamanho do Jpeg e menor a qualidade (neste caso já está no máximo)
jpeg.CompressionQuality:=100;
jpeg.SaveToFile('C:\Windows\System32\screen' + inttostr(dia) + '.' + inttostr(mes) + '.' + inttostr(ano) + '.' + inttostr(hora) + '.' + inttostr(min) + '.' + inttostr(seg) + '.jpg');

jpeg.Free;
Bmp.Free;

end;


O QUE PODERIA SER FEITO AÍ PRA SOBRESCREVER O PRIMEIRO JPEG QUE É ARQUIVADO EM CONJUNTO COM O BMP? vale falar também que o BMP só é arquivado uma única vez (que é a primeira) depois só vem JPEG, daí queria fazer a sobrescrição para em síntese, sempre ficar 1 JPEG arquivado entende?
Responder

Gostei + 0

19/10/2012

Marcos Rocha

Pelo seu código, cada vez que o timer dispara ele gera um novo jpeg na pasta Windows\System32. Se eu estiver entendendo o que você quer, basta passar o nome do último jpeg salvo para uma variável global e remover o último jpeg antes de salvar o novo.
var
  GLOBAL_LAST_SHOT: String;

procedure TForm1.Timer3Timer(Sender: TObject);
var
  bmp : TBitmap;
  jpeg : TJPEGImage;
  sNovoPrintScreen: String;
begin
  //Convertendo a variável
  DecodeDate(now,ano,mes,dia);
  DecodeTime(now,hora,min,seg,mseg);
  sNovoPrintScreen := 'C:\Windows\System32\screen' + inttostr(dia) + '.' + inttostr(mes) + '.' + inttostr(ano) + '.' + inttostr(hora) + '.' + inttostr(min) + '.' + inttostr(seg) + '.jpg';
  Bmp := TBitmap.Create;
  jpeg := TJpegImage.Create;
  // *capturar uma foto da tela
  try
    Image1.picture.Assign(CaptureScreenRect(Rect(0,0,Screen.DesktopWidth,Screen.DesktopHeight)));
    Image1.picture.SaveToFile('C:\Windows\System32\screen.bmp');
    
    Bmp.LoadFromFile('C:\Windows\System32\screen.bmp');  
    jpeg.Assign(bmp);
    
    //TODO: Implementar uma rotina que não exclua o último screenshot válido
    if (Trim(GLOBAL_LAST_SHOT) <> '') and (FileExists(GLOBAL_LAST_SHOT)) then
      DeleteFile(GLOBAL_LAST_SHOT);
      // Quanto menor o valor, menor o tamanho do Jpeg e menor a qualidade (neste caso já está no máximo)
      jpeg.CompressionQuality:=100;
    jpeg.SaveToFile(sNovoPrintScreen);
    
    GLOBAL_LAST_SHOT := sNovoPrintScreen;
  finally  
    jpeg.Free;
    Bmp.Free;
  end;
end;
Responder

Gostei + 0

19/10/2012

Luiz Eduardo

EU CONSEGUI SOBRESCREVER O BMP, MAS O JPEG DA CONVERSÃO NÃO. Olha como ficou:

procedure TForm1.Timer3Timer(Sender: TObject);

var bmp : TBitmap;
jpeg : TJPEGImage;

begin

// *capturar uma foto da tela

Image1.picture.Assign(CaptureScreenRect(Rect(0,0,Screen.DesktopWidth,Screen.DesktopHeight)));
Image1.picture.SaveToFile('C:\Windows\System32\Screen.bmp');

Bmp := TBitmap.Create;
Bmp.LoadFromFile('C:\Windows\System32\Screen.bmp');
jpeg := TJpegImage.Create;
jpeg.Assign(bmp);

if FileExists('C:\Windows\System32\Screen.bmp') then

Bmp.Free;
jpeg.Free;

end;


Responder

Gostei + 0

19/10/2012

Luiz Eduardo

VALEU MARCOS!! AS MODIFICAÇÕES QUE VC FEZ FUNCIONOU PERFEITAMNTE, DEPOIS TESTEI COM PACIÊNCIA E DEU CERTO, ESTAVA DANDO ERRO DEVIDO A UNS PARÊNTESES E PONTO E VÍRGULA QUE AINDA FALTAVAM RSRS. ERA EXATAMENTE ISSO QUE EU QUERIA!! BRIGADÃO MESMO COLEGA!!

Agora me diga uma coisa:

É possível fazero mesmo procedimento para sobrescrever videos armazenados em AVI? Porque eu to usando uma função da API do Windows pra capturar uma webcam, entretanto como você sabe avi é um formato muito grande e ocupa muito espaço. Será que funcionava essa modificação aí no armazenamento, assim como funcionou com os jpeg's? to te mandando o código pra vc ver se tem condição, irei testar aqui também agora!



COD:




//Handle das funções de capturar a webcam

var
hWndC : THandle = 0;

implementation

//API que se comunica com a Cam

function capCreateCaptureWindowA(lpszWindowName : PCHAR; dwStyle : longint; x : integer;
y : integer;nWidth : integer;nHeight : integer;ParentWin : HWND; nId : integer): HWND; STDCALL EXTERNAL 'AVICAP32.DLL';


{$R *.dfm}

const WM_CAP_START = WM_USER;
const WM_CAP_STOP = WM_CAP_START + 68;
const WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10;
const WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11;
const WM_CAP_SAVEDIB = WM_CAP_START + 25;
const WM_CAP_GRAB_FRAME = WM_CAP_START + 60;
const WM_CAP_SEQUENCE = WM_CAP_START + 62;
const WM_CAP_FILE_SET_CAPTURE_FILEA = WM_CAP_START + 20;
const WM_CAP_SEQUENCE_NOFILE =WM_CAP_START+ 63;
const WM_CAP_SET_OVERLAY =WM_CAP_START+ 51 ;
const WM_CAP_SET_PREVIEW =WM_CAP_START+ 50;
const WM_CAP_SET_CALLBACK_VIDEOSTREAM = WM_CAP_START +6;
const WM_CAP_SET_CALLBACK_ERROR=WM_CAP_START +2;
const WM_CAP_SET_CALLBACK_STATUSA= WM_CAP_START +3;
const WM_CAP_SET_CALLBACK_FRAME= WM_CAP_START +5;
const WM_CAP_SET_SCALE=WM_CAP_START+ 53 ;
const WM_CAP_SET_PREVIEWRATE=WM_CAP_START+ 52;


/Liga a Webcam
procedure TForm1.Timer4Timer(Sender: TObject);

begin

if hWndC <> 0 then exit;
hWndC := capCreateCaptureWindowA('WebCam no Turbo Delphi',WS_CHILD or WS_VISIBLE ,Panel1.Left,Panel1.Top,320,240,Form1.Handle,0);

if hWndC <> 0 then
begin
SendMessage(hWndC, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0);
SendMessage(hWndC, WM_CAP_SET_CALLBACK_ERROR, 0, 0);
SendMessage(hWndC, WM_CAP_SET_CALLBACK_STATUSA, 0, 0);
SendMessage(hWndC, WM_CAP_DRIVER_CONNECT, 0, 0);
SendMessage(hWndC, WM_CAP_SET_SCALE, 1, 0);
SendMessage(hWndC, WM_CAP_SET_PREVIEWRATE, 66, 0);
SendMessage(hWndC, WM_CAP_SET_OVERLAY, 1, 0);
SendMessage(hWndC, WM_CAP_SET_PREVIEW, 1, 0);

//Salva o video em avi

if hWndC <> 0 then
begin
SendMessage(hWndC,WM_CAP_FILE_SET_CAPTURE_FILEA,0, Longint(pchar('c:\Windows\System32\Video.avi')));
SendMessage(hWndC, WM_CAP_SEQUENCE, 0, 0);
SendMessage(hWndC, WM_CAP_STOP, 0, 0);
SendMessage(hWndC, WM_CAP_DRIVER_DISCONNECT, 0, 0);

end;
end;
Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar