Logo Море(!) аналитической информации!
IT-консалтинг Software Engineering Программирование СУБД Безопасность Internet Сети Операционные системы Hardware
Архив форумов ЦИТФорума
Море(!) вопросов - Море(!) ответов
 
 FAQFAQ   ПоискПоиск   ПользователиПользователи   ГруппыГруппы   РегистрацияРегистрация 
 ПрофильПрофиль   Войти и проверить личные сообщенияВойти и проверить личные сообщения   ВходВход 
Как правильно задавать вопросы

Запись AVI

 
Перейти:  
Этот форум закрыт, вы не можете писать новые сообщения и редактировать старые.   Эта тема закрыта, вы не можете писать ответы и редактировать сообщения.    Список форумов Архив форумов ЦИТФорума -> Программирование
Предыдущая тема :: Следующая тема  
Автор Сообщение
Mike



Зарегистрирован: 17.11.2001
Сообщения: 339
Откуда: ekb

СообщениеДобавлено: Пн Авг 30 2004 06:47    Заголовок сообщения: Запись AVI Ответить с цитатой

Кто-нибудь сталкивался с записью ави-файлов ? Как использовать кодеки, установленные в системе, как записывать звук в нужном формате ? Где брать информацию по этой теме ?
Вернуться к началу
Посмотреть профиль Отправить личное сообщение Отправить e-mail
GREA



Зарегистрирован: 14.05.2003
Сообщения: 758
Откуда: Новосибирск

СообщениеДобавлено: Пн Авг 30 2004 19:35    Заголовок сообщения: Ответить с цитатой

У меня есть к тебе вопрос. Такой банальный, что и задавать не хочется. На чем пишешь?!!!
У меня где-то лежал компонент Дельфи (еле нашел в инете) для записи AVI.
С компонентами для си, ситуация проще. Попробуй поисковики.
Вернуться к началу
Посмотреть профиль Отправить личное сообщение
Mike



Зарегистрирован: 17.11.2001
Сообщения: 339
Откуда: ekb

СообщениеДобавлено: Вт Авг 31 2004 06:02    Заголовок сообщения: Ответить с цитатой

Пишу я на С++Бильдере 5
Но это не имеет значения, потому что вызов нужных процедур происходит при помощи интерфейсов, но вот где взять подробную информацию об этом ? В инете я пока только отрывочные примеры видел.
Вернуться к началу
Посмотреть профиль Отправить личное сообщение Отправить e-mail
GREA



Зарегистрирован: 14.05.2003
Сообщения: 758
Откуда: Новосибирск

СообщениеДобавлено: Вт Авг 31 2004 07:47    Заголовок сообщения: Ответить с цитатой

Копируй Wink
unit AviWriter;
{=====================================================================}
{=========== Дополонено Прокофьевым В.А. в июне 2002г : ============}
{===== а) компрессия; б) дозапись в AVI-файл по одному фрэйму ======}
{===== в) при отсутствии звука временый файл не создаётся, ======}
{===== а при наличии звука временый файл компрессированный ======}
{==== Компонент тестировался под Delphi 5.0, Windows 2000/XP ====}
{==== С.Петербург ВНИИГ им.Веденеева ProkKlim@Hydro.vniig.ru ====}
{=====================================================================}

///////////////////////////////////////////////////////////////////////
// //
// AviWriter -- a component to create rudimentary AVI files //
// by Elliott Shevin, with large pieces of code //
// stolen from Anders Melander //
// //
///////////////////////////////////////////////////////////////////////
// //
// AviWriter will build an AVI file containing one stream of any //
// number of TBitmaps, plus a single WAV file. //
// //
// * Properties * //
// NewFrame : A pointers to TBitmap object which become //
// frames of the AVI video stream. //
// Height, Width: //
// The dimensions of the AVI video, in pixels, -1 =Auto //
// FrameTime: //
// The duration of each video frame, in milliseconds. //
// Stretch: If TRUE, each TBitmap on the Bitmaps list is //
// stretches to the dimensions specified in Height //
// and Width. If FALSE, each TBitmap is copied from //
// its upper left corner without stretching. //
// WAVFileName: //
// The name of a WAV file which will become the audio //
// stream for the AVI. Optional. //
// Compression: //
// = True for MSVC compression for AVI-file //
// //
// * Methods * //
// BeginCreateAVI: //
// Creates the AVI file named by FileName. //
// AddVideoFrame: //
// Adds the new frame to AVI-file // //
// EndCreateAVI: //
// Adds sound & resume AVI-file //
// //
///////////////////////////////////////////////////////////////////////

interface

uses Windows,Messages, SysUtils, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls,
{$ifdef VER90}
Ole2;
{$else}
ActiveX;
{$endif}

///////////////////////////////////////////////////////////////////////
// //
// Video for Windows //
// //
///////////////////////////////////////////////////////////////////////
// //
// Adapted from Thomas Schimming's VFW.PAS //
// (c) 1996 Thomas Schimming, schimmin@iee1.et.tu-dresden.de //
// (c) 1998,99 Anders Melander //
// //
///////////////////////////////////////////////////////////////////////
// //
// Ripped all COM/ActiveX stuff and added some AVI stream functions. //
// //
///////////////////////////////////////////////////////////////////////

type LONG = LongInt;

// TAVIFileInfo dwFlag values

const
AVIErr_BADFORMAT = $80044066; // MAKE_AVIErr(102)
AVIErr_MEMORY = $80044067; // MAKE_AVIErr(103)
AVIErr_FILEREAD = $8004406D; // MAKE_AVIErr(109)
AVIErr_FILEOPEN = $8004406F; // MAKE_AVIErr(111)

const AVIErr_OK = 0;
AVIIF_KEYFRAME = $10;

StreamTypeVIDEO = $73646976; // DWORD( 'v', 'i', 'd', 's' )
StreamTypeAUDIO = $73647561; // DWORD( 'a', 'u', 'd', 's' )

{========== Добавлены константы из модуля VFW.pas (12.06.02) =========}
const AVICOMPRESSF_INTERLEAVE = $00000001; // interleave
AVICOMPRESSF_DATARATE = $00000002; // use a data rate
AVICOMPRESSF_KEYFRAMES = $00000004; // use keyframes
AVICOMPRESSF_VALID = $00000008; // has valid data?

type TAVIStreamInfoA = record
fccType,
fccHandler,
dwFlags, // Contains AVITF_* flags
dwCaps: DWORD;
wPriority,
wLanguage: WORD;
dwScale,
dwRate, // dwRate / dwScale == samples/second
dwStart,
dwLength, // In units above...
dwInitialFrames,
dwSuggestedBufferSize,
dwQuality,
dwSampleSize: DWORD;
rcFrame: TRect;
dwEditCount,
dwFormatChangeCount: DWORD;
szName: array[0..63] of AnsiChar;
end;
TAVIStreamInfo = TAVIStreamInfoA;
pAVIStreamInfo = ^TAVIStreamInfo;
{=====================================================================}

pAVIStream = Pointer;
ApAVIStream = array[0..1] of pAVIStream;
pAVIFile = Pointer;
TAVISaveCallback = function(nPercent: Integer): LONG; stdcall;

type TAVICompressOptions = packed record
fccType : DWORD;
fccHandler : DWORD;
dwKeyFrameEvery : DWORD;
dwQuality : DWORD;
dwBytesPerSecond : DWORD;
dwFlags : DWORD;
lpFormat : Pointer;
cbFormat : DWORD;
lpParms : Pointer;
cbParms : DWORD;
dwInterleaveEvery : DWORD;
end;
PAVICompressOptions = ^TAVICompressOptions;
APAVICompressOptions = array[0..1] of PAVICompressOptions;

{=====================================================================}
procedure AVIFileInit; stdcall; external 'avifil32.dll';
procedure AVIFileExit; stdcall; external 'avifil32.dll';
function AVIFileOpen(var ppfile: pAVIFile; szFile: PChar;
uMode: UINT; lpHandler: Pointer): HResult;
stdcall; external 'avifil32.dll';
function AVIFileCreateStream(pfile: pAVIFile; var ppavi: pAVIStream;
var psi: TAVIStreamInfo): HResult;
stdcall; external 'avifil32.dll';
function AVIStreamSetFormat(pavi: pAVIStream; lPos: LONG;
lpFormat: Pointer; cbFormat: LONG): HResult;
stdcall; external 'avifil32.dll';
function AVIStreamWrite(pavi: pAVIStream; lStart, lSamples: LONG;
lpBuffer: Pointer; cbBuffer: LONG; dwFlags: DWORD;
var plSampWritten: LONG; var plBytesWritten: LONG): HResult;
stdcall; external 'avifil32.dll'
function AVIStreamRelease(pavi: pAVIStream): ULONG;
stdcall; external 'avifil32.dll';
function AVIFileRelease(pfile: pAVIFile): ULONG;
stdcall; external 'avifil32.dll';
function AVIFileGetStream(pfile: pAVIFile; var ppavi: pAVIStream;
fccType: DWORD; lParam: LONG): HResult;
stdcall; external 'avifil32.dll';
function CreateEditableStream(var ppsEditable: pAVIStream;
psSource: pAVIStream): HResult;
stdcall; external 'avifil32.dll';
function AVISaveV(szFile: PChar; pclsidHandler: PCLSID;
lpfnCallback: TAVISaveCallback; nStreams: Integer; pavi:
ApAVIStream; lpOptions: APAVICompressOptions): HResult;
stdcall; external 'avifil32.dll';
function AVIMakeCompressedStream(var ppsCompressed: pAVIStream;
ppsSource: pAVIStream; lpOptions: PAVICompressOptions;
pclsidHandler: PCLSID): HResult;
stdcall; external 'avifil32.dll';
{=====================================================================}

type TAviWriter = class(TComponent)
private { Private declarations }
pFile: pAVIFile;
fNewFrame: TBitmap;
fHeight, fWidth, fFrameTime, fFramesCount: Integer;
fStretch, fCompression: Boolean;
fWavFileName, fFileName, TempFile: TFileName;
VideoStream, pStream: pAVIStream;
procedure AddAudio;
procedure InternalGetDIBSizes(Bitmap: HBitmap;
var InfoHeaderSize: Integer; var ImageSize: LongInt;
PixelFormat: TPixelFormat);
function InternalGetDIB(Bitmap: HBitmap; Palette: HPalette;
var BitmapInfo; var Bits; PixelFormat: TPixelFormat): Boolean;
procedure InitializeBitmapInfoHeader(Bitmap: HBitmap;
var Info: TBitmapInfoHeader; PixelFormat: TPixelFormat);
procedure SetWavFileName(const Value: TFileName);
public { Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeginCreateAVI(const FileName: TFileName);
procedure AddVideoFrame; { Добавление очередного фрэйма }
procedure EndCreateAVI; { Добавл-е звукового потока и закрытие }
property NewFrame: TBitmap read fNewFrame write fNewFrame;
property FramesCount: Integer read fFramesCount; { счётчик }
published { Published declarations }
{-- Параметры фрэймов следует задавать ДО вызова CreateAVIFile: ---}
property Height: Integer read fHeight write fHeight; { -1 = Auto }
property Width: Integer read fWidth write fWidth; { -1 = Auto }
property FrameTime: Integer read fFrameTime write fFrameTime;
property Stretch: Boolean read fStretch write fStretch;
property WavFileName: TFileName read fWavFileName
write SetWavFileName;
property Compression: Boolean read fCompression write fCompression;
end;

procedure Register;

implementation

{=====================================================================}
procedure Register;
begin RegisterComponents('Lib_PVA', [TAviWriter]) end;

{=====================================================================}
constructor TAviWriter.Create(AOwner : TComponent);
var L: Integer; TempDir: TFileName;
begin
Inherited Create(AOwner);
fHeight := -1; fWidth := -1; { По умолчанию - Auto sizes mode }
fFrameTime := 300; fStretch := True;
fFramesCount := 0; { Обнуляем счётчик фрэймов }
{ По умолчанию компрессия есть - на порядок уменьшает размер файла }
fCompression := True;
AVIFileInit;
NewFrame := TBitmap.Create;
{ Задаём имя временного файла по умолчанию }
SetLength(TempDir, Max_Path + 1);
L := GetTempPath(Max_Path, PChar(TempDir));
SetLength(TempDir, L);
If Copy(TempDir, Length(TempDir), 1) <> '\'
then TempDir := TempDir + '\';
TempFile := TempDir + '~Temp.avi';
end;

{=====================================================================}
destructor TAviWriter.Destroy;
begin
AviFileExit; NewFrame.Free;
Inherited;
end;

{==== Функция перевода в Four-Character code (добавлено 12.06.02) ====}
function MyFOURCC(const Ch1, Ch2, Ch3, Ch4: Char): DWord;
begin
Result:= Ord(Ch1) + Ord(Ch2) shl 8 + Ord(Ch3) shl 16 + Ord(Ch4) shl 24;
end;

{=====================================================================}
{==================== Начало создания AVI-файла ====================}
{=====================================================================}
procedure TAviWriter.BeginCreateAVI(const FileName: TFileName);
var StreamInfo: TAVIStreamInfo; CompOptions: PAVICompressOptions;
MyAVIcompressOptions: TAVICompressOptions;
begin
// Open AVI file for Write & Read
Try
If AVIFileOpen(pFile, PChar(FileName), of_Write or of_Create
or of_Read or of_Share_Exclusive, nil) <> AVIErr_OK then raise
Exception.Create('Failed to create AVI-file');
fFileName := FileName;
// Write the stream header
FillChar(StreamInfo, SizeOf(StreamInfo), 0);
// Set frame rate and scale
With StreamInfo do begin
dwRate := 1000;
dwScale := fFrameTime;
fccType := StreamTypeVIDEO;
fccHandler := 0;
dwFlags := 0;
dwSuggestedBufferSize := 0;
rcFrame.Right := Self.Width;
rcFrame.Bottom := Self.Height;
end;
// Open AVI data stream
If AVIFileCreateStream(pFile, pStream, StreamInfo) <> AVIErr_OK
then raise Exception.Create('Failed to create AVI video stream');
{.............. Задаём параметры компрессии AVI-файла ................}
If fCompression then with MyAVIcompressOptions do begin
fccType := StreamTypeVideo; // DWORD
fccHandler := MyFOURCC('M','S','V','C'); // DWORD
{ Диап-н Quality [0..10000] - уменьшение на размер файла влияет слабо }
dwQuality := 10000; // DWORD
dwFlags := AVICompressF_VALID; // DWORD
CompOptions := @MyAVIcompressOptions;
end else CompOptions := nil;
{------ Создаём на базе pStream сжатый видео-поток VideoStream -------}
If AVIMakeCompressedStream(VideoStream, pStream,
CompOptions, nil) <> AVIErr_OK then
raise Exception.Create('Could not create Compressed Stream');
except { ...при этом сам файл тоже будет небольшим }
end;
end;

{=====================================================================}
{============= Добавление одного видео-фрэйма (кадра) ================}
{=====================================================================}
procedure TAviWriter.AddVideoFrame;
var BitmapInfoSize, AVIErr: Integer;
BitmapInfo: PBitmapInfoHeader; Bitmap: TBitmap;
BitmapSize: LongInt; BitmapBits: Pointer;
PixFor: TPixelFormat; Samples_Written, Bytes_Written: LONG;
begin { Чтобы не было Warning: }
BitmapInfo := nil; BitmapBits := nil; Bitmap := nil;
Inc(fFramesCount); { Счётчик записанных в видеопоток кадров (фрэймов) }
Try
// Allocate the bitmap to which the NewFrame bitmap will be copied
Bitmap := TBitmap.Create;
{ При задании размеров <= 0 они вычисляются автоматически }
If Self.Width <= 0 then Bitmap.Width := NewFrame.Width
else Bitmap.Width := Self.Width;
If Self.Height <= 0 then Bitmap.Height := NewFrame.Height
else Bitmap.Height := Self.Height;
{================== Write new bitmap to the stream ===================}
BitmapInfo := nil; BitmapBits := nil;
// Copy the bitmap from the NewFrame bitmap, stretching if
// desired. If the caller elects not to stretch, use the first pixel
// in the bitmap as a background color in case either the height or
// width of the source is smaller than the output.
// If Draw fails, do a StretchDraw.
PixFor := NewFrame.PixelFormat; { Добавлено 12.06.02 }
If not (PixFor in [pf4bit, pf8bit, pf15bit, pf16bit,
pf24bit, pf32bit]) then PixFor := pf8bit;
If fStretch then Bitmap.Canvas.StretchDraw(Rect(0, 0,
Self.Width, Self.Height), NewFrame)
else with Bitmap.Canvas do try
Brush.Color := NewFrame.Canvas.Pixels[0,0];
Brush.Style := bsSolid;
FillRect(Rect(0, 0, Bitmap.Width, Bitmap.Height));
Draw(0,0,NewFrame);
except
Bitmap.Canvas.StretchDraw(Rect(0, 0,
Self.Width, Self.Height), NewFrame);
end;
// Determine size of DIB
InternalGetDIBSizes(Bitmap.Handle, BitmapInfoSize,
BitmapSize, PixFor);
If (BitmapInfoSize = 0) then raise Exception.Create(
'Failed to retrieve bitmap info');
// Get DIB header and pixel buffers
GetMem(BitmapInfo, BitmapInfoSize);
GetMem(BitmapBits, BitmapSize);
InternalGetDIB(Bitmap.Handle,0, BitmapInfo^, BitmapBits^, PixFor);
// On the first time through, set the stream format
If fFramesCount=1 then if AVIStreamSetFormat(VideoStream, 0,
BitmapInfo, BitmapInfoSize) <> AVIErr_OK then raise
Exception.Create('Failed to set AVI stream format');
// Write new frame to the video stream
AVIErr := AVIStreamWrite(VideoStream, fFramesCount-1, 1,
BitmapBits, BitmapSize, AVIIF_KEYFRAME,
Samples_Written, Bytes_Written);
If AVIErr <> AVIErr_OK then raise Exception.Create(
'Failed to add frame to AVI. Err=' + IntToHex(AVIErr,Cool);
finally
If (BitmapInfo <> nil) then FreeMem(BitmapInfo);
If (BitmapBits <> nil) then FreeMem(BitmapBits);
Bitmap.Free;
end;
end;

{=====================================================================}
{=== Добавл. звука (если он есть) и завершение работы с AVI-файлом ===}
{=====================================================================}
procedure TAviWriter.EndCreateAVI;
begin
Try
AviStreamRelease(pStream); AviStreamRelease(VideoStream);
DeleteFile(TempFile); { На всякий случай }
If WavFileName <> '' then begin
If not FileExists(WavFileName) then raise Exception.Create(
'The sound file ' + WavFileName + ' not exists');
AddAudio; { ...здесь создаётся новый TempFile }
end;
finally
Repeat until AviFileRelease(pFile) <= 0;
fFramesCount := 0; { Для следующего запуска }
end;
{------ Удаление и переименование файлов после добавления звука ------}
If FileExists(TempFile) then try
DeleteFile(fFileName); RenameFile(TempFile, fFileName);
except
DeleteFile(TempFile);
end;
end;

{==================== Добавляем в файл AudioStream ===================}
procedure TAviWriter.AddAudio;
var pAudioFile: pAVIFile; HR: Double; AudioStream: pAVIStream;
Streams: ApAVIStream; CompOptions: APAVICompressOptions;
begin
// Open the audio file. Round(HR-...) добавлено 12.06.02- иначе Warning
Try
HR := AVIFileOpen(pAudioFile, PChar(WavFileName), of_Read, nil);
If HR <> 0 then begin
If Round(HR - AVIErr_BADFORMAT)=0 then raise Exception.Create(
'The file could not be read, indicating ' +
'a corrupt file or an unrecognized format.') else
if Round(HR - AVIErr_MEMORY)=0 then raise Exception.Create(
'The file could not be opened because of insufficient memory.')
else
if Round(HR - AVIErr_FILEREAD)=0 then raise Exception.Create(
'A disk error occurred while reading the audio file.') else
if Round(HR - AVIErr_FILEOPEN)=0 then raise Exception.Create(
'A disk error occurred while opening the audio file.') else
if Round(HR - REGDB_E_CLASSNOTREG)=0 then
raise Exception.Create(
'According to the registry, the type of audio file specified' +
' in AVIFileOpen does not have a handler to process it.') else
raise Exception.Create('Unknown error opening audio file');
end;
// Open the audio stream
If AVIFileGetStream(pAudioFile, AudioStream, 0, 0) <> AVIErr_OK
then raise Exception.Create('Unable to get audio stream');
Try { Заново открываем VideoStream (без этого не пойдёт!) }
If AVIFileGetStream(pFile, VideoStream, 0, 0) <> AVIErr_OK
then raise Exception.Create('Unable to get video stream');
{ Читаем видеопоток из созданного файла pFile (FileName), а звуковой }
{ поток- из открытого файла pAudioFile (WavFileName), и записывем всё }
{ во временный файл TempFile. Потом в EndCreateAVI переименуем фалы. }
Streams[0] := VideoStream; CompOptions[0] := nil;
Streams[1] := AudioStream; CompOptions[1] := nil;
If AVISaveV(PChar(TempFile), nil, nil,
2, Streams, CompOptions) <> AVIErr_OK then
raise Exception.Create('Failed to add AVI audio stream');
finally
AviStreamRelease(VideoStream); AviStreamRelease(AudioStream);
end;
finally
AviFileRelease(pAudioFile);
end;
end;

// --------------
// InternalGetDIB
// --------------
// Converts a bitmap to a DIB of a specified PixelFormat.
//
// Parameters:
// Bitmap The handle of the source bitmap.
// Pal The handle of the source palette.
// BitmapInfo The buffer that will receive the DIB's TBitmapInfo
// structure.
// A buffer of sufficient size must have been allocated
// prior to calling this function.
// Bits The buffer that will receive the DIB's pixel data.
// A buffer of sufficient size must have been allocated
// prior to calling this function.
// PixelFormat The pixel format of the destination DIB.
//
// Returns:
// True on success, False on failure.
//
// Note: The InternalGetDIBSizes function can be used to calculate the
// nescessary sizes of the BitmapInfo and Bits buffers.

{=====================================================================}
function TAviWriter.InternalGetDIB(Bitmap: HBitmap; Palette: HPalette;
var BitmapInfo; var Bits; PixelFormat: TPixelFormat): Boolean;
// From graphics.pas, "optimized" for our use
var OldPal: HPalette; DC: HDC;
begin
InitializeBitmapInfoHeader(Bitmap, TBitmapInfoHeader(BitmapInfo),
PixelFormat);
OldPal := 0; DC := CreateCompatibleDC(0);
Try
If (Palette <> 0) then begin
OldPal := SelectPalette(DC, Palette, False);
RealizePalette(DC);
end;
Result := (GetDIBits(DC, Bitmap, 0,
Abs(TBitmapInfoHeader(BitmapInfo).biHeight),
@Bits, TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0);
finally
If (OldPal <> 0) then SelectPalette(DC, OldPal, False);
DeleteDC(DC);
end;
end;

// -------------------
// InternalGetDIBSizes
// -------------------
// Calculates the buffer sizes nescessary for convertion of a bitmap
// to a DIBof a specified PixelFormat.
// See the GetDIBSizes API function for more info.
//
// Parameters:
// Bitmap The handle of the source bitmap.
// InfoHeaderSize The returned size of a buffer that will receive
// the DIB's TBitmapInfo structure.
// ImageSize The returned size of a buffer that will receive
// the DIB'spixel data.
// PixelFormat The pixel format of the destination DIB.

{=====================================================================}
procedure TAviWriter.InternalGetDIBSizes(Bitmap: HBitmap;
var InfoHeaderSize: Integer; var ImageSize: LongInt;
PixelFormat: TPixelFormat);
// From graphics.pas, "optimized" for our use
var Info: TBitmapInfoHeader;
begin
InitializeBitmapInfoHeader(Bitmap, Info, PixelFormat);
// Check for palette device format
If (Info.biBitCount > Cool then begin
// Header but no palette
InfoHeaderSize := SizeOf(TBitmapInfoHeader);
If ((Info.biCompression and BI_BITFIELDS) <> 0) then
Inc(InfoHeaderSize, 12);
// Header and palette
end else InfoHeaderSize := SizeOf(TBitmapInfoHeader) +
SizeOf(TRGBQuad) * (1 shl Info.biBitCount);
ImageSize := Info.biSizeImage;
end;

// --------------------------
// InitializeBitmapInfoHeader
// --------------------------
// Fills a TBitmapInfoHeader with the values of a bitmap when
// converted to a DIB of a specified PixelFormat.
//
// Parameters:
// Bitmap The handle of the source bitmap.
// Info The TBitmapInfoHeader buffer that will receive the values.
// PixelFormat The pixel format of the destination DIB.

{=====================================================================}
procedure TAviWriter.InitializeBitmapInfoHeader(Bitmap: HBitmap;
var Info: TBitmapInfoHeader; PixelFormat: TPixelFormat);
// From graphics.pas, "optimized" for our use
var DIB: TDIBSection; Bytes: Integer;
function AlignBit(Bits, BitsPerPixel, Alignment: Cardinal): Cardinal;
begin
Dec(Alignment);
Result := ((Bits * BitsPerPixel) + Alignment) and not Alignment;
Result := Result shr 3;
end;
begin
DIB.dsbmih.biSize := 0;
Bytes := GetObject(Bitmap, SizeOf(DIB), @DIB);
If (Bytes = 0) then raise Exception.Create('Invalid bitmap');
If (Bytes >= (SizeOf(DIB.dsbm) + SizeOf(DIB.dsbmih))) and
(DIB.dsbmih.biSize >= SizeOf(DIB.dsbmih)) then Info := DIB.dsbmih
else begin
FillChar(Info, SizeOf(Info), 0);
With Info, DIB.dsbm do begin
biSize := SizeOf(Info);
biWidth := bmWidth; biHeight := bmHeight;
end;
end;
{.....................................................................}
Case PixelFormat of
pf1bit: Info.biBitCount := 1;
pf4bit: Info.biBitCount := 4;
pf8bit: Info.biBitCount := 8;
pf15bit: Info.biBitCount := 15; { Дополнено 12.06.02 }
pf16bit: Info.biBitCount := 16;
pf24bit: Info.biBitCount := 24;
pf32bit: Info.biBitCount := 32;
else raise Exception.Create('Invalid pixel foramt');
end;
Info.biPlanes := 1;
Info.biCompression := BI_RGB; // Always return data in RGB format
Info.biSizeImage := AlignBit(Info.biWidth, Info.biBitCount, 32) *
Cardinal(Abs(Info.biHeight));
end;

{=====================================================================}
procedure TAviWriter.SetWavFileName(const Value: TFileName);
begin
If LowerCase(fWavFileName) <> LowerCase(Value) then begin
If (Value <> '') and (LowerCase(ExtractFileExt(Value)) <> '.wav')
then raise Exception.Create(
'WavFileName must name a file with the .wav extension')
else fWavFileName := Value;
end;
end;

end.
Вернуться к началу
Посмотреть профиль Отправить личное сообщение
Mike



Зарегистрирован: 17.11.2001
Сообщения: 339
Откуда: ekb

СообщениеДобавлено: Вт Авг 31 2004 09:28    Заголовок сообщения: Ответить с цитатой

Спасибо, попробую разобраться Smile)
Вернуться к началу
Посмотреть профиль Отправить личное сообщение Отправить e-mail
Показать сообщения:   
Этот форум закрыт, вы не можете писать новые сообщения и редактировать старые.   Эта тема закрыта, вы не можете писать ответы и редактировать сообщения.    Список форумов Архив форумов ЦИТФорума -> Программирование Часовой пояс: GMT + 3
Страница 1 из 1

 
Перейти:  
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах


Powered by phpBB © 2001, 2002 phpBB Group
Русская поддержка phpBB

 

IT-консалтинг Software Engineering Программирование СУБД Безопасность Internet Сети Операционные системы Hardware

Информация для рекламодателей PR-акции, размещение рекламы — adv@citforum.ru,
тел. +7 495 6608306, ICQ 232284597
Пресс-релизы — pr@citforum.ru
Послать комментарий
Информация для авторов
This Web server launched on February 24, 1997
Copyright © 1997-2000 CIT, © 2001-2006 CIT Forum
Внимание! Любой из материалов, опубликованных на этом сервере, не может быть воспроизведен в какой бы то ни было форме и какими бы то ни было средствами без письменного разрешения владельцев авторских прав. Подробнее...